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.

Fix GGUF export writing outside the chosen save directory on Windows (#7897) (#7937)

Daniel Han9bc00afcf654
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py
index 4979ebd48d6..4c3d124fc04 100644
--- a/studio/backend/core/export/export.py
+++ b/studio/backend/core/export/export.py
@@ -168,6 +168,31 @@ def _supports_kwarg(fn, name):
return name in params or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
+def _reported_gguf_files(result):
+ """Absolute GGUF paths unsloth reported writing, or None if it reported nothing.
+
+ None means "fall back to the legacy heuristics", which covers every older shape:
+ pre-2025.10 unsloth returned nothing, is_main_process=False returns None, and
+ save_method="lora" returns a str. An empty result is None too, since a stale
+ manifest is indistinguishable from an old build.
+ """
+ if not isinstance(result, dict):
+ return None
+ files = result.get("gguf_files")
+ if not isinstance(files, (list, tuple)):
+ return None
+
+ resolved = []
+ for entry in files:
+ # A malformed payload must not be half-trusted.
+ if not isinstance(entry, (str, os.PathLike)):
+ return None
+ path = os.path.abspath(os.fspath(entry))
+ if path.lower().endswith(".gguf") and os.path.isfile(path):
+ resolved.append(path)
+ return resolved or None
+
+
def _compressed_export_supported():
"""True if the installed unsloth build can do FP8/NVFP4 compressed-tensors export."""
try:
@@ -1049,13 +1074,48 @@ class ExportBackend:
_model_tmp = os.path.join(abs_save_dir, f"_tmp_model_{uuid.uuid4().hex[:8]}")
model_tmp_to_cleanup = _model_tmp
- self.current_model.save_pretrained_gguf(
+ _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}/"
+ )
+
+ # 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):
@@ -1069,7 +1129,9 @@ class ExportBackend:
continue
if sub.name in pre_existing_subs:
continue
- for src in sub.glob("*.gguf"):
+ # 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")):
dest = os.path.join(abs_save_dir, src.name)
shutil.move(str(src), dest)
logger.info(f"Relocated GGUF: {src.name} → {abs_save_dir}/")
@@ -1094,15 +1156,32 @@ class ExportBackend:
shutil.rmtree(str(gguf_dir), ignore_errors = True)
logger.info(f"Cleaned up intermediate GGUF dir: {gguf_dir}")
- # Write export metadata so the Chat page can identify the base model
- self._write_export_metadata(abs_save_dir)
-
- final_ggufs = sorted(glob.glob(os.path.join(abs_save_dir, "*.gguf")))
+ # iterdir, not glob.glob: glob hides dot-leading names, so an empty
+ # model stem's ".Q4_K_M.gguf" got reported as "(none)".
+ final_ggufs = sorted(
+ str(p)
+ for p in Path(abs_save_dir).iterdir()
+ if p.is_file() and p.name.lower().endswith(".gguf")
+ )
logger.info(
"GGUF export complete. Final files in %s:\n %s",
abs_save_dir,
"\n ".join(os.path.basename(f) for f in final_ggufs) or "(none)",
)
+ if not final_ggufs:
+ # Reporting success over an empty directory is what hid #7897.
+ shutil.rmtree(model_tmp_to_cleanup, ignore_errors = True)
+ return (
+ False,
+ f"GGUF conversion reported success but wrote no .gguf file to "
+ f"{abs_save_dir}. Check the export log for the path the "
+ f"converter actually used, then upgrade with "
+ f"`pip install --upgrade unsloth unsloth_zoo` and retry.",
+ None,
+ )
+
+ # Only write metadata once an artifact is actually present.
+ self._write_export_metadata(abs_save_dir)
output_path = str(Path(abs_save_dir).resolve())
if push_to_hub:
@@ -1229,7 +1308,12 @@ class ExportBackend:
# Forward the token so convert_lora_to_gguf.py can fetch a gated base's config.
token = hf_token or None,
)
- final_ggufs = sorted(glob.glob(os.path.join(save_directory, "*.gguf")))
+ # iterdir, not glob.glob: glob hides dot-leading names.
+ final_ggufs = sorted(
+ str(p)
+ for p in Path(save_directory).iterdir()
+ if p.is_file() and p.name.lower().endswith(".gguf")
+ )
logger.info(
"LoRA GGUF export complete. Files in %s:\n %s",
save_directory,
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index 83253be566a..81624a0c8da 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -597,6 +597,7 @@ class TrainingStatus(BaseModel):
"loading_dataset",
"configuring",
"training",
+ "finalizing",
"completed",
"error",
"stopped",
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index eb355ebda06..126d4543bdf 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -98,6 +98,21 @@ logger = get_logger(__name__)
_PROGRESS_STALL_TIMEOUT_POLLS = 1800 # ~30 min at 1 poll/sec
+def _is_finalizing(progress, msg_lower: str) -> bool:
+ """Worker alive past the last step, `complete` not yet drained.
+
+ The post-training save emits no step updates, so the bar sat at 100% labelled
+ "training" for its whole duration, indistinguishable from a hang. Non-terminal
+ by design: the last step means the optimizer loop ended, not that the save
+ succeeded, so completion still comes solely from is_completed.
+ """
+ if any(k in msg_lower for k in ("saving", "merging")):
+ return True
+ total = getattr(progress, "total_steps", 0) or 0
+ step = getattr(progress, "step", 0) or 0
+ return total > 0 and step >= total
+
+
def _validate_local_dataset_paths(paths: list[str], label: str = "Local dataset") -> list[str]:
"""Resolve and validate a list of local dataset paths. Returns validated absolute paths."""
validated = []
@@ -722,6 +737,8 @@ async def get_training_status(current_subject: str = Depends(get_current_subject
phase = "loading_model"
elif any(k in msg_lower for k in ["preparing", "initializing", "configuring"]):
phase = "configuring"
+ elif _is_finalizing(progress, msg_lower):
+ phase = "finalizing"
else:
phase = "training"
elif trainer_stopped:
diff --git a/studio/backend/tests/test_export_gguf_discovery.py b/studio/backend/tests/test_export_gguf_discovery.py
new file mode 100644
index 00000000000..bfddd294686
--- /dev/null
+++ b/studio/backend/tests/test_export_gguf_discovery.py
@@ -0,0 +1,321 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""GGUF export must find its output, or fail honestly (#7897).
+
+save_pretrained_gguf already returns the files it wrote, but export_gguf discarded
+that and guessed: cwd, new subdirs of the save dir, and a `<checkpoint>_gguf` dir.
+A GGUF written anywhere else, as a Windows local base-model path caused, was
+invisible, and the export still reported success over an empty directory.
+
+Reuses the harness in test_export_absolute_paths.py.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_TESTS_DIR = Path(__file__).resolve().parent
+_BACKEND_DIR = _TESTS_DIR.parent
+if str(_BACKEND_DIR) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_DIR))
+if str(_TESTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_TESTS_DIR))
+
+from test_export_absolute_paths import ( # noqa: E402
+ _install_export_backend_stubs,
+ _load_module,
+)
+
+
+def _backend(
+ monkeypatch,
+ tmp_path,
+ model,
+ checkpoint = None,
+):
+ """An ExportBackend wired to `model`, exporting into tmp_path/'export'."""
+ _install_export_backend_stubs(monkeypatch)
+ export_mod = _load_module("test_core_export_backend", "core/export/export.py", monkeypatch)
+
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+ save_dir = tmp_path / "export"
+ monkeypatch.chdir(cwd)
+ monkeypatch.setattr(export_mod, "resolve_export_write_dir", lambda _value: save_dir)
+
+ backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)
+ backend.current_model = model
+ backend.current_tokenizer = object()
+ backend.current_checkpoint = checkpoint
+ return export_mod, backend, save_dir, cwd
+
+
+def _gguf(path: Path, payload: bytes = b"GGUF") -> Path:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(payload)
+ return path
+
+
+# _reported_gguf_files: the "is this build telling us anything?" contract.
+
+
+ "result",
+ [
+ None, # pre-2025.10 unsloth / non-main process
+ "some/path", # save_method="lora" returns a str
+ ("path", True, False), # hypothetical legacy tuple
+ {}, # dict without the key
+ {"gguf_files": None},
+ {"gguf_files": "not-a-list"},
+ {"gguf_files": []}, # empty == "nothing to say"
+ {"gguf_files": [123]}, # malformed entry -> distrust all
+ ],
+ ids = [
+ "none",
+ "str",
+ "tuple",
+ "empty_dict",
+ "null_files",
+ "str_files",
+ "empty_list",
+ "bad_entry",
+ ],
+)
+def test_reported_files_absent_shapes_fall_back(monkeypatch, tmp_path, result):
+ export_mod, _b, _s, _c = _backend(monkeypatch, tmp_path, object())
+ assert export_mod._reported_gguf_files(result) is None
+
+
+def test_reported_files_filters_missing_and_non_gguf(monkeypatch, tmp_path):
+ export_mod, _b, _s, _c = _backend(monkeypatch, tmp_path, object())
+ real = _gguf(tmp_path / "a" / "Model.Q4_K_M.gguf")
+ out = export_mod._reported_gguf_files(
+ {
+ "gguf_files": [
+ str(real),
+ str(tmp_path / "a" / "deleted.gguf"), # unlinked by cleanup
+ str(tmp_path / "a" / "notes.txt"), # not a gguf
+ str(tmp_path / "a"), # a directory
+ ]
+ }
+ )
+ assert out == [str(real)]
+
+
+def test_reported_files_accepts_future_keys(monkeypatch, tmp_path):
+ export_mod, _b, _s, _c = _backend(monkeypatch, tmp_path, object())
+ real = _gguf(tmp_path / "a" / "Model.Q4_K_M.gguf")
+ out = export_mod._reported_gguf_files(
+ {"gguf_files": [str(real)], "some_future_field": 1, "is_vlm": True}
+ )
+ assert out == [str(real)]
+
+
+# Table B: where the fake exporter puts its output.
+
+
+def test_gguf_beside_base_model_is_relocated(monkeypatch, tmp_path):
+ """The #7897 shape: output lands outside the save dir, cwd and checkpoint."""
+ sibling = tmp_path / "Models" / "Merged Models"
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ Path(model_save_path).mkdir(parents = True)
+ stray = _gguf(sibling / "MyModel.Q5_K_M.gguf")
+ return {"gguf_files": [str(stray)]}
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ success, message, output_path = 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 (sibling / "MyModel.Q5_K_M.gguf").exists()
+ assert output_path == str(save_dir.resolve())
+
+
+def test_zero_files_is_a_failure_not_a_silent_success(monkeypatch, tmp_path):
+ """Old unsloth (no manifest) plus a lost output must not report success."""
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ Path(model_save_path).mkdir(parents = True)
+ _gguf(tmp_path / "elsewhere" / "MyModel.Q5_K_M.gguf")
+ return None # legacy build
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ success, message, output_path = backend.export_gguf(str(save_dir), "q5_k_m")
+
+ assert success is False
+ assert str(save_dir) in message
+ assert "no .gguf" in message
+ assert output_path is None
+ assert list(save_dir.glob("_tmp_model_*")) == []
+
+
+def test_nested_gguf_is_rescued_before_rmtree(monkeypatch, tmp_path):
+ """The flatten pass rmtree's every new subdir; sharded output sat one deeper."""
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ tmp = Path(model_save_path)
+ tmp.mkdir(parents = True)
+ gguf_dir = Path(str(tmp) + "_gguf") / "shards"
+ for i in (1, 2, 3):
+ _gguf(gguf_dir / f"MyModel-{i:05d}-of-00003.gguf")
+ return None # exercise the fallback path
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ success, message, _p = backend.export_gguf(str(save_dir), "q5_k_m")
+
+ assert success is True, message
+ names = sorted(p.name for p in save_dir.glob("*.gguf"))
+ assert names == [
+ "MyModel-00001-of-00003.gguf",
+ "MyModel-00002-of-00003.gguf",
+ "MyModel-00003-of-00003.gguf",
+ ]
+
+
+def test_hidden_gguf_is_reported_not_none(monkeypatch, tmp_path):
+ """An empty model stem produced '.Q5_K_M.gguf'; glob.glob could not see it.
+
+ A reporting defect, not file loss: the flatten pass uses Path.glob, which does
+ match dot-leading names, so the file was in place while the log said "(none)".
+ Still bites, because zero-files is now a failure: reverting the listing to
+ glob.glob would fail this export outright.
+ """
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ tmp = Path(model_save_path)
+ tmp.mkdir(parents = True)
+ _gguf(Path(str(tmp) + "_gguf") / ".Q5_K_M.gguf")
+ return None
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ success, message, _p = backend.export_gguf(str(save_dir), "q5_k_m")
+
+ assert success is True, message
+ assert (save_dir / ".Q5_K_M.gguf").is_file()
+
+
+def test_files_already_in_place_are_not_moved_onto_themselves(monkeypatch, tmp_path):
+ """The normal PEFT path already lands inside the save dir."""
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ Path(model_save_path).mkdir(parents = True)
+ here = _gguf(tmp_path / "export" / "MyModel.Q5_K_M.gguf")
+ return {"gguf_files": [str(here)]}
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ 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").read_bytes() == b"GGUF"
+
+
+def test_multi_quant_relocates_every_output(monkeypatch, tmp_path):
+ sibling = tmp_path / "beside"
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ Path(model_save_path).mkdir(parents = True)
+ files = [
+ str(_gguf(sibling / f"MyModel.{q}.gguf")) for q in ("Q4_K_M", "Q5_K_M", "Q8_0")
+ ]
+ return {"gguf_files": files}
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ success, message, _p = backend.export_gguf(str(save_dir), ["q4_k_m", "q5_k_m", "q8_0"])
+
+ assert success is True, message
+ assert sorted(p.name for p in save_dir.glob("*.gguf")) == [
+ "MyModel.Q4_K_M.gguf",
+ "MyModel.Q5_K_M.gguf",
+ "MyModel.Q8_0.gguf",
+ ]
+ assert list(sibling.glob("*.gguf")) == []
+
+
+def test_vlm_mmproj_companion_is_relocated(monkeypatch, tmp_path):
+ sibling = tmp_path / "beside"
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ Path(model_save_path).mkdir(parents = True)
+ return {
+ "gguf_files": [
+ str(_gguf(sibling / "MyVLM.Q4_K_M.gguf")),
+ str(_gguf(sibling / "MyVLM.F16-mmproj.gguf")),
+ ]
+ }
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ success, message, _p = backend.export_gguf(str(save_dir), "q4_k_m")
+
+ assert success is True, message
+ assert (save_dir / "MyVLM.Q4_K_M.gguf").is_file()
+ assert (save_dir / "MyVLM.F16-mmproj.gguf").is_file()
+
+
+def test_modelfile_is_relocated_not_deleted(monkeypatch, tmp_path):
+ """The Modelfile lived in the temp *_gguf dir the flatten pass rmtree's."""
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ tmp = Path(model_save_path)
+ tmp.mkdir(parents = True)
+ gguf_dir = Path(str(tmp) + "_gguf")
+ out = _gguf(gguf_dir / "MyModel.Q5_K_M.gguf")
+ mf = gguf_dir / "Modelfile"
+ mf.write_text("FROM ./MyModel.Q5_K_M.gguf\n")
+ return {"gguf_files": [str(out)], "modelfile_location": str(mf)}
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ success, message, _p = backend.export_gguf(str(save_dir), "q5_k_m")
+
+ assert success is True, message
+ assert (save_dir / "Modelfile").is_file()
+ assert (save_dir / "MyModel.Q5_K_M.gguf").is_file()
+
+
+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.
+ """
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ Path(model_save_path).mkdir(parents = True)
+ return None
+
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ save_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
+
+
+def test_cleanup_failure_does_not_lose_reported_files(monkeypatch, tmp_path):
+ """Windows locks make rmtree(ignore_errors=True) a silent no-op."""
+ sibling = tmp_path / "beside"
+
+ class _Model:
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ Path(model_save_path).mkdir(parents = True)
+ return {"gguf_files": [str(_gguf(sibling / "MyModel.Q5_K_M.gguf"))]}
+
+ export_mod, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())
+ monkeypatch.setattr(export_mod.shutil, "rmtree", lambda *a, **k: None)
+
+ 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()
diff --git a/studio/backend/tests/test_training_finalizing_phase.py b/studio/backend/tests/test_training_finalizing_phase.py
new file mode 100644
index 00000000000..22cfb1420b5
--- /dev/null
+++ b/studio/backend/tests/test_training_finalizing_phase.py
@@ -0,0 +1,169 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The post-training save must be visible, and must stay non-terminal (#7897).
+
+After the last optimizer step the worker still merges and saves, emitting no step
+updates, so /api/train/status reported phase="training" at 100% throughout,
+indistinguishable from a hang. The `finalizing` phase names it.
+
+Two invariants matter more than the label:
+ 1. Reaching total_steps must never imply completion; `completed` still comes
+ only from progress.is_completed.
+ 2. Every phase the route emits must be in TrainingStatus's Literal, or pydantic
+ raises ValidationError and the blanket handler turns /status into a 500.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_TESTS_DIR = Path(__file__).resolve().parent
+_BACKEND_DIR = _TESTS_DIR.parent
+if str(_BACKEND_DIR) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_DIR))
+
+_ROUTES_TRAINING = _BACKEND_DIR / "routes" / "training.py"
+_MODELS_TRAINING = _BACKEND_DIR / "models" / "training.py"
+
+
+def _load_is_finalizing():
+ """Exec just the helper: routes/training.py pulls in the whole app otherwise."""
+ src = _ROUTES_TRAINING.read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == "_is_finalizing":
+ ns: dict = {}
+ exec(compile(ast.Module([node], []), str(_ROUTES_TRAINING), "exec"), ns)
+ return ns["_is_finalizing"]
+ raise AssertionError("routes/training.py does not define _is_finalizing")
+
+
+def _progress(step = 0, total_steps = 0):
+ return SimpleNamespace(step = step, total_steps = total_steps)
+
+
+# _is_finalizing
+
+
+ "step, total, msg, expected",
+ [
+ (126, 126, "training in progress...", True), # the reported symptom
+ (127, 126, "training in progress...", True), # defensive overshoot
+ (125, 126, "training in progress...", False), # steps remain
+ (0, 126, "training in progress...", False),
+ (0, 0, "training in progress...", False), # total unknown -> inert
+ (5, 0, "training in progress...", False),
+ (0, 0, "saving model...", True), # MLX/embedding say so
+ (10, 126, "saving stopped model...", True),
+ (10, 126, "merging weights into 16bit", True),
+ (10, 126, "ready to train", False),
+ ],
+)
+def test_is_finalizing(step, total, msg, expected):
+ assert _load_is_finalizing()(_progress(step, total), msg) is expected
+
+
+def test_is_finalizing_tolerates_missing_attributes():
+ """A progress object may be None or partial early in a run."""
+ fn = _load_is_finalizing()
+ assert fn(None, "training") is False
+ assert fn(SimpleNamespace(), "training") is False
+ assert fn(SimpleNamespace(step = None, total_steps = None), "training") is False
+
+
+# Contract guards
+
+
+def _phase_literals() -> set[str]:
+ src = _MODELS_TRAINING.read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.ClassDef) and node.name == "TrainingStatus"):
+ continue
+ for stmt in node.body:
+ if (
+ isinstance(stmt, ast.AnnAssign)
+ and isinstance(stmt.target, ast.Name)
+ and stmt.target.id == "phase"
+ ):
+ sub = stmt.annotation
+ # phase: Literal[...] = Field(...)
+ while isinstance(sub, ast.Subscript) and not (
+ isinstance(sub.value, ast.Name) and sub.value.id == "Literal"
+ ):
+ sub = sub.value
+ literal = sub.slice
+ elts = literal.elts if isinstance(literal, ast.Tuple) else [literal]
+ return {e.value for e in elts if isinstance(e, ast.Constant)}
+ raise AssertionError("TrainingStatus.phase Literal not found")
+
+
+def test_every_emitted_phase_is_in_the_response_literal():
+ """A phase missing from the Literal makes /api/train/status 500, not degrade."""
+ src = _ROUTES_TRAINING.read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ fn = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and n.name == "get_training_status"
+ )
+ emitted = {
+ node.value.value
+ for node in ast.walk(fn)
+ if isinstance(node, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "phase" for t in node.targets)
+ and isinstance(node.value, ast.Constant)
+ and isinstance(node.value.value, str)
+ }
+ assert emitted, "no literal phase assignments found; guard needs updating"
+ missing = emitted - _phase_literals()
+ assert not missing, f"phases emitted but not declared in TrainingStatus: {sorted(missing)}"
+
+
+def test_finalizing_is_declared():
+ assert "finalizing" in _phase_literals()
+
+
+def test_completion_still_comes_only_from_is_completed():
+ """100% must not be promoted to a terminal state."""
+ src = _ROUTES_TRAINING.read_text(encoding = "utf-8")
+ fn_src = ast.get_source_segment(
+ src,
+ next(
+ n
+ for n in ast.walk(ast.parse(src))
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and n.name == "get_training_status"
+ ),
+ )
+ completed_branch = re.search(r'phase\s*=\s*"completed"', fn_src)
+ assert completed_branch, "no completed branch found"
+ preceding = fn_src[: completed_branch.start()]
+ # The guard immediately governing `completed` must still be is_completed.
+ assert (
+ "is_completed" in preceding.rsplit("elif", 1)[-1]
+ ), "the `completed` phase is no longer gated on progress.is_completed"
+ # And `finalizing` must sit inside the is_active branch, never after it.
+ assert fn_src.index('phase = "finalizing"') < completed_branch.start()
+
+
+def test_frontend_phase_union_covers_the_backend_literal():
+ """phaseColors/phaseLabelKeys are Record<TrainingPhase, ...>, so a backend
+ phase missing from the union is a compile error the frontend never sees."""
+ runtime_ts = (
+ _BACKEND_DIR.parent / "frontend" / "src" / "features" / "training" / "types" / "runtime.ts"
+ )
+ if not runtime_ts.is_file():
+ pytest.skip("frontend sources not present")
+ union = set(re.findall(r'\|\s*"([a-z_]+)"', runtime_ts.read_text(encoding = "utf-8")))
+ missing = _phase_literals() - union
+ assert not missing, f"TrainingPhase is missing backend phases: {sorted(missing)}"
diff --git a/studio/frontend/src/features/studio/sections/progress-section-lib.ts b/studio/frontend/src/features/studio/sections/progress-section-lib.ts
index 6b18301f8e3..2ab2c8ee5ef 100644
--- a/studio/frontend/src/features/studio/sections/progress-section-lib.ts
+++ b/studio/frontend/src/features/studio/sections/progress-section-lib.ts
@@ -16,6 +16,9 @@ export const phaseColors: Record<TrainingPhase, string> = {
configuring: "bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",
training:
"bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",
+ // Busy, not done: amber like the other working states, never completed green.
+ finalizing:
+ "bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",
completed:
"bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",
error: "bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300",
diff --git a/studio/frontend/src/features/studio/sections/progress-section.tsx b/studio/frontend/src/features/studio/sections/progress-section.tsx
index a2cf7112966..f4604a2396c 100644
--- a/studio/frontend/src/features/studio/sections/progress-section.tsx
+++ b/studio/frontend/src/features/studio/sections/progress-section.tsx
@@ -68,6 +68,7 @@ const phaseLabelKeys = {
loading_dataset: "studio.progress.phase.loadingDataset",
configuring: "studio.progress.phase.configuring",
training: "studio.progress.phase.training",
+ finalizing: "studio.progress.phase.finalizing",
completed: "studio.progress.phase.completed",
error: "studio.progress.phase.error",
stopped: "studio.progress.phase.stopped",
diff --git a/studio/frontend/src/features/training/types/runtime.ts b/studio/frontend/src/features/training/types/runtime.ts
index 373e8766532..27d2e1dfd30 100644
--- a/studio/frontend/src/features/training/types/runtime.ts
+++ b/studio/frontend/src/features/training/types/runtime.ts
@@ -9,6 +9,8 @@ export type TrainingPhase =
| "loading_dataset"
| "configuring"
| "training"
+ // Steps done, worker still saving. Non-terminal: 100% is not success.
+ | "finalizing"
| "completed"
| "error"
| "stopped";
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index a5da006f13f..c49302de3c3 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1534,6 +1534,7 @@ export const ar = {
loadingDataset: "جارٍ تحميل مجموعة البيانات",
configuring: "جارٍ الإعداد",
training: "قيد التدريب",
+ finalizing: "جارٍ حفظ النموذج",
completed: "مكتمل",
error: "خطأ",
stopped: "متوقف",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 94d3b4c6131..1cd71eb1eb2 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1592,6 +1592,7 @@ export const de = {
loadingDataset: "Datensatz wird geladen",
configuring: "Wird konfiguriert",
training: "Training",
+ finalizing: "Modell wird gespeichert",
completed: "Abgeschlossen",
error: "Fehler",
stopped: "Gestoppt",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 3ab3659fb0b..66b12238514 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1527,6 +1527,7 @@ export const en = {
loadingDataset: "Loading dataset",
configuring: "Configuring",
training: "Training",
+ finalizing: "Saving model",
completed: "Completed",
error: "Error",
stopped: "Stopped",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index cbab5e85b9b..c91b03295b1 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1587,6 +1587,7 @@ export const es = {
loadingDataset: "Cargando conjunto de datos",
configuring: "Configurando",
training: "Entrenando",
+ finalizing: "Guardando modelo",
completed: "Completado",
error: "Error",
stopped: "Detenido",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index e28eda175f8..7207d428a61 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1592,6 +1592,7 @@ export const fr = {
loadingDataset: "Chargement du jeu de données",
configuring: "Configuration",
training: "Entraînement",
+ finalizing: "Enregistrement du modèle",
completed: "Terminé",
error: "Erreur",
stopped: "Arrêté",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 9ee301ffba5..4a302fbd8cd 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1538,6 +1538,7 @@ export const hi = {
loadingDataset: "डेटासेट लोड हो रहा है",
configuring: "कॉन्फ़िगर हो रहा है",
training: "ट्रेनिंग हो रही है",
+ finalizing: "मॉडल सेव हो रहा है",
completed: "पूर्ण",
error: "त्रुटि",
stopped: "रोका गया",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 2c7c17b11ad..9c40e1b974e 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1587,6 +1587,7 @@ export const it = {
loadingDataset: "Caricamento del dataset",
configuring: "Configurazione",
training: "Addestramento",
+ finalizing: "Salvataggio del modello",
completed: "Completato",
error: "Errore",
stopped: "Fermato",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 8461aec9835..5df57d5068c 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1475,6 +1475,7 @@ export const ja = {
loadingDataset: "データセットを読み込み中",
configuring: "構成中",
training: "トレーニング中",
+ finalizing: "モデルを保存中",
completed: "完了",
error: "エラー",
stopped: "停止",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 439d2e530a1..28db6d5a035 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1534,6 +1534,7 @@ export const ko = {
loadingDataset: "데이터셋 로딩 중",
configuring: "구성 중",
training: "학습 중",
+ finalizing: "모델 저장 중",
completed: "완료됨",
error: "오류",
stopped: "중지됨",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 8a0b1811d4b..04a7007205f 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1543,6 +1543,7 @@ export const ptBR = {
loadingDataset: "Carregando dataset",
configuring: "Configurando",
training: "Treinando",
+ finalizing: "Salvando modelo",
completed: "Concluído",
error: "Erro",
stopped: "Interrompido",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index e6633a674c6..aa9a40161d1 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1547,6 +1547,7 @@ export const ru = {
loadingDataset: "Загрузка датасета",
configuring: "Настройка",
training: "Обучение",
+ finalizing: "Сохранение модели",
completed: "Завершено",
error: "Ошибка",
stopped: "Остановлено",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 97dfd840205..ad395ae8200 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1478,6 +1478,7 @@ export const zhCN = {
loadingDataset: "正在加载数据集",
configuring: "配置中",
training: "训练中",
+ finalizing: "正在保存模型",
completed: "已完成",
error: "错误",
stopped: "已停止",
diff --git a/studio/frontend/tests/export-progress-percent.test.ts b/studio/frontend/tests/export-progress-percent.test.ts
new file mode 100644
index 00000000000..cfe22c019b2
--- /dev/null
+++ b/studio/frontend/tests/export-progress-percent.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register("./helpers/export-store-resolver.mjs", import.meta.url);
+
+const { selectExportProgressPercent, isExportPanelActive } = await import(
+ "../src/features/export/stores/export-runtime-store.ts"
+);
+
+type Percentable = Parameters<typeof selectExportProgressPercent>[0];
+
+/** Only the fields the selectors read; the rest of the store is irrelevant here. */
+function state(partial: Record<string, unknown>): Percentable {
+ return {
+ phase: "idle",
+ quantTotal: 1,
+ quantIndex: 0,
+ isExporting: false,
+ ...partial,
+ } as unknown as Percentable;
+}
+
+test("idle is 0 and loading is a fixed 8", () => {
+ assert.equal(selectExportProgressPercent(state({ phase: "idle" })), 0);
+ assert.equal(selectExportProgressPercent(state({ phase: "loading" })), 8);
+});
+
+test("an active export never reaches 100 - the band stops at 87", () => {
+ const band = (quantIndex: number, quantTotal: number) =>
+ selectExportProgressPercent(state({ phase: "exporting", quantIndex, quantTotal }));
+
+ assert.equal(band(0, 4), 15);
+ assert.equal(band(2, 4), 51);
+ assert.equal(band(4, 4), 87);
+ // 100% must mean "finished", never "still working".
+ for (let i = 0; i <= 8; i++) {
+ assert.ok(band(i, 4) < 100, `quantIndex=${i} reached 100 while exporting`);
+ }
+});
+
+test("quantIndex beyond quantTotal clamps instead of overshooting", () => {
+ assert.equal(
+ selectExportProgressPercent(state({ phase: "exporting", quantIndex: 99, quantTotal: 4 })),
+ 87,
+ );
+ assert.equal(
+ selectExportProgressPercent(state({ phase: "exporting", quantIndex: -5, quantTotal: 4 })),
+ 15,
+ );
+});
+
+test("a zero or negative quantTotal does not divide by zero", () => {
+ // NaN is deliberately not covered: runExport always sets quantTotal to
+ // Math.max(1, quantLevels.length) and applyBackendStatus never touches it, so
+ // a non-numeric quantTotal is unreachable. Math.max(1, NaN) would be NaN.
+ for (const quantTotal of [0, -1]) {
+ const value = selectExportProgressPercent(
+ state({ phase: "exporting", quantIndex: 1, quantTotal }),
+ );
+ assert.ok(Number.isFinite(value), `quantTotal=${quantTotal} produced ${value}`);
+ assert.ok(value >= 15 && value <= 87, `quantTotal=${quantTotal} produced ${value}`);
+ }
+});
+
+test("only success reports 100", () => {
+ assert.equal(selectExportProgressPercent(state({ phase: "success" })), 100);
+ for (const phase of ["idle", "loading", "exporting", "error", "canceled"]) {
+ assert.notEqual(
+ selectExportProgressPercent(state({ phase, quantIndex: 4, quantTotal: 4 })),
+ 100,
+ `${phase} reported 100`,
+ );
+ }
+});
+
+test("error and canceled freeze near where they stopped instead of snapping to 0", () => {
+ for (const phase of ["error", "canceled"]) {
+ assert.equal(
+ selectExportProgressPercent(state({ phase, quantIndex: 2, quantTotal: 4 })),
+ 51,
+ );
+ assert.equal(selectExportProgressPercent(state({ phase, quantIndex: 0, quantTotal: 4 })), 15);
+ }
+});
+
+test("the panel stays visible for terminal phases, not just active ones", () => {
+ assert.equal(isExportPanelActive(state({ phase: "idle", isExporting: false })), false);
+ assert.equal(isExportPanelActive(state({ phase: "idle", isExporting: true })), true);
+ for (const phase of ["loading", "exporting", "success", "error", "canceled"]) {
+ assert.equal(isExportPanelActive(state({ phase, isExporting: false })), true, phase);
+ }
+});
diff --git a/studio/frontend/tests/helpers/export-api-stub.mjs b/studio/frontend/tests/helpers/export-api-stub.mjs
new file mode 100644
index 00000000000..533694c8bae
--- /dev/null
+++ b/studio/frontend/tests/helpers/export-api-stub.mjs
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Stands in for src/features/export/api/export-api.ts.
+//
+// The real module reaches authFetch -> features/auth/index.ts -> login-page.tsx, and
+// node --experimental-strip-types cannot parse JSX, so importing the export store for
+// a unit test would pull in the whole React tree. Cutting the chain here keeps the
+// state machine testable without touching the shared bundler-resolver. Calls are
+// recorded on `calls` and answered from `responses`, so a test can drive runExport
+// end to end without a server.
+
+export const calls = [];
+export const responses = new Map();
+
+function record(name) {
+ return async (...args) => {
+ calls.push({ name, args });
+ const answer = responses.get(name);
+ if (typeof answer === "function") return answer(...args);
+ if (answer instanceof Error) throw answer;
+ return answer ?? { success: true, message: "ok", details: null };
+ };
+}
+
+export function resetStub() {
+ calls.length = 0;
+ responses.clear();
+}
+
+export const loadCheckpoint = record("loadCheckpoint");
+export const exportGGUF = record("exportGGUF");
+export const exportMerged = record("exportMerged");
+export const exportLoRA = record("exportLoRA");
+export const cleanupExport = record("cleanupExport");
+export const cancelExport = record("cancelExport");
+export const getExportStatus = record("getExportStatus");
+
+export function isRecoverableTransportError() {
+ return false;
+}
diff --git a/studio/frontend/tests/helpers/export-store-resolver.mjs b/studio/frontend/tests/helpers/export-store-resolver.mjs
new file mode 100644
index 00000000000..ec4a95cbc8e
--- /dev/null
+++ b/studio/frontend/tests/helpers/export-store-resolver.mjs
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// bundler-resolver's two rules, plus one redirect: export-api -> a stub.
+// See export-api-stub.mjs for why the redirect is needed.
+import { existsSync } from "node:fs";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const SRC = fileURLToPath(new URL("../../src/", import.meta.url));
+const STUB = new URL("./export-api-stub.mjs", import.meta.url).href;
+
+function firstExisting(base) {
+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
+ if (existsSync(candidate)) return pathToFileURL(candidate).href;
+ }
+ return null;
+}
+
+export function resolve(specifier, context, next) {
+ if (/(^|\/)(\.\.\/)*api\/export-api(\.ts)?$/.test(specifier)) {
+ return next(STUB, context);
+ }
+ if (specifier.startsWith("@/")) {
+ const resolved = firstExisting(SRC + specifier.slice(2));
+ return next(resolved ?? specifier, context);
+ }
+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {
+ const resolved = firstExisting(fileURLToPath(new URL(specifier, context.parentURL)));
+ if (resolved) return next(resolved, context);
+ }
+ return next(specifier, context);
+}
diff --git a/studio/frontend/tests/training-progress-pin.test.ts b/studio/frontend/tests/training-progress-pin.test.ts
new file mode 100644
index 00000000000..c180395162b
--- /dev/null
+++ b/studio/frontend/tests/training-progress-pin.test.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Why this file exists (unslothai/unsloth#7897): the training bar sat at 100%
+ * with no completion. `applyStatus` never touches `progressPercent`, so once the
+ * SSE has reported step N/N the bar stays at 100 no matter what phase the status
+ * poll then reports. Reaching 100% means the optimizer loop ended -- NOT that the
+ * model save succeeded -- so completion must come from the phase, never the bar.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { useTrainingRuntimeStore, shouldShowTrainingView } = await import(
+ "../src/features/training/stores/training-runtime-store.ts"
+);
+
+function reset() {
+ useTrainingRuntimeStore.setState(
+ useTrainingRuntimeStore.getInitialState?.() ?? {},
+ true,
+ );
+}
+
+function status(partial: Record<string, unknown>) {
+ return {
+ job_id: "job-1",
+ phase: "idle",
+ is_training_running: false,
+ message: "",
+ error: null,
+ details: null,
+ metric_history: null,
+ ...partial,
+ } as never;
+}
+
+function progress(partial: Record<string, unknown>) {
+ return {
+ job_id: "job-1",
+ step: 0,
+ total_steps: 126,
+ loss: 0.5,
+ learning_rate: 1e-4,
+ progress_percent: 0,
+ epoch: 1,
+ elapsed_seconds: 1,
+ eta_seconds: null,
+ grad_norm: null,
+ num_tokens: null,
+ eval_loss: null,
+ ...partial,
+ } as never;
+}
+
+test("100% does not imply completion - the bar stays pinned while phase goes idle", () => {
+ reset();
+ const store = useTrainingRuntimeStore.getState();
+ store.applyProgress(progress({ step: 126, progress_percent: 100 }), 126);
+
+ assert.equal(useTrainingRuntimeStore.getState().progressPercent, 100);
+ assert.equal(useTrainingRuntimeStore.getState().currentStep, 126);
+
+ // The status poll settles the run without a `completed` phase.
+ useTrainingRuntimeStore.getState().applyStatus(
+ status({ phase: "idle", is_training_running: false }),
+ );
+
+ const after = useTrainingRuntimeStore.getState();
+ assert.equal(after.phase, "idle");
+ // This is the reported symptom: a bar reading 100% with nothing terminal.
+ assert.equal(after.progressPercent, 100);
+ assert.equal(after.currentStep, 126);
+ // ...and the view stays mounted because currentStep > 0, so the user sees it.
+ assert.equal(shouldShowTrainingView(after), true);
+});
+
+test("a real completion is carried by the phase, not the percentage", () => {
+ reset();
+ const store = useTrainingRuntimeStore.getState();
+ store.applyProgress(progress({ step: 126, progress_percent: 100 }), 126);
+ store.applyStatus(status({ phase: "completed", is_training_running: false }));
+
+ const after = useTrainingRuntimeStore.getState();
+ assert.equal(after.phase, "completed");
+ assert.equal(after.isTrainingRunning, false);
+});
+
+test("the post-training save is visible as its own phase, not silent 'training'", () => {
+ reset();
+ const store = useTrainingRuntimeStore.getState();
+ store.applyProgress(progress({ step: 126, progress_percent: 100 }), 126);
+ store.applyStatus(
+ status({
+ phase: "finalizing",
+ is_training_running: true,
+ message: "Saving model...",
+ }),
+ );
+
+ const after = useTrainingRuntimeStore.getState();
+ assert.equal(after.phase, "finalizing");
+ // Still running, so live sync/SSE must stay on.
+ assert.equal(after.isTrainingRunning, true);
+ assert.equal(after.progressPercent, 100);
+});
+
+test("applyStatus clears stopRequested once the run is no longer running", () => {
+ reset();
+ useTrainingRuntimeStore.setState({ stopRequested: true } as never);
+ useTrainingRuntimeStore
+ .getState()
+ .applyStatus(status({ phase: "training", is_training_running: true }));
+ assert.equal(useTrainingRuntimeStore.getState().stopRequested, true);
+
+ useTrainingRuntimeStore
+ .getState()
+ .applyStatus(status({ phase: "completed", is_training_running: false }));
+ assert.equal(useTrainingRuntimeStore.getState().stopRequested, false);
+});
+
+test("a non-finite loss at a NEW step clears the display instead of going stale", () => {
+ reset();
+ const store = useTrainingRuntimeStore.getState();
+ store.applyProgress(progress({ step: 10, loss: 0.42 }), 10);
+ assert.equal(useTrainingRuntimeStore.getState().currentLoss, 0.42);
+
+ // Backend reports a non-finite loss as null at a later step.
+ useTrainingRuntimeStore.getState().applyProgress(progress({ step: 11, loss: null }), 11);
+ assert.equal(useTrainingRuntimeStore.getState().currentLoss, null);
+});
+
+test("a null loss at the SAME step keeps the last good value", () => {
+ reset();
+ const store = useTrainingRuntimeStore.getState();
+ store.applyProgress(progress({ step: 10, loss: 0.42 }), 10);
+ useTrainingRuntimeStore.getState().applyProgress(progress({ step: 10, loss: null }), 10);
+ assert.equal(useTrainingRuntimeStore.getState().currentLoss, 0.42);
+});
diff --git a/tests/test_gguf_basename_platform_matrix.py b/tests/test_gguf_basename_platform_matrix.py
new file mode 100644
index 00000000000..d780164f8c0
--- /dev/null
+++ b/tests/test_gguf_basename_platform_matrix.py
@@ -0,0 +1,149 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""[Windows, Linux, WSL, macOS] x [NVIDIA, AMD/ROCm, CPU-only] for the #7897 fix.
+
+The fix is pure path arithmetic and imports no GPU library, so the GPU axis is an
+invariance check: the stem and its destination must be byte-identical in every
+cell. No per-vendor expectations are invented, because none exist.
+
+UNSLOTH_SIM_GPU (nvidia|rocm|cpu) picks the cell and is applied at import, since the
+spoofs mutate torch globals and cannot be undone in-process. One process per cell.
+The OS axis is monkeypatch-scoped and needs no isolation.
+"""
+
+from __future__ import annotations
+
+import ast
+import ntpath
+import os
+import posixpath
+import sys
+from pathlib import Path
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parent.parent
+_SAVE_PY = _REPO_ROOT / "unsloth" / "save.py"
+
+_GPU_CELL = os.environ.get("UNSLOTH_SIM_GPU", "cpu").lower()
+
+
+# -- GPU cell: applied before anything torch-touching -------------------------
+
+
+def _apply_gpu_cell(cell: str) -> dict:
+ """Returns a description of what the process now claims to be."""
+ if cell == "cpu":
+ return {"cell": "cpu", "cuda": False, "hip": None}
+
+ sys.path.insert(0, str(_REPO_ROOT / "tests"))
+ if cell == "nvidia":
+ import _zoo_aggressive_cuda_spoof as spoof
+ spoof.apply()
+ elif cell == "rocm":
+ import _zoo_rocm_spoof as spoof
+
+ # gfx1100 == RX 7900 XTX, the card in issue #7897.
+ spoof.apply("gfx1100")
+ else:
+ raise AssertionError(f"unknown UNSLOTH_SIM_GPU={cell!r}")
+
+ import torch
+
+ return {
+ "cell": cell,
+ "cuda": torch.cuda.is_available(),
+ "hip": getattr(torch.version, "hip", None),
+ }
+
+
+try:
+ _GPU_STATE = _apply_gpu_cell(_GPU_CELL)
+except Exception as exc: # noqa: BLE001 -- torch absent is a legitimate cell
+ _GPU_STATE = {"cell": _GPU_CELL, "error": str(exc)}
+
+
+# -- The helper under test, lifted without importing unsloth ------------------
+
+
+def _load_helper():
+ src = _SAVE_PY.read_text(encoding = "utf-8")
+ for node in ast.parse(src).body:
+ if isinstance(node, ast.FunctionDef) and node.name == "_model_basename":
+ ns: dict = {"os": os}
+ exec(compile(ast.Module([node], []), str(_SAVE_PY), "exec"), ns)
+ return ns["_model_basename"]
+ raise AssertionError("unsloth/save.py defines no _model_basename")
+
+
+# OS flavour -> (path module, a base-model path that OS actually produces)
+_OS_CELLS = {
+ "windows": (ntpath, r"D:\Models\Merged Models\MyModel"),
+ "linux": (posixpath, "/home/u/models/MyModel"),
+ # WSL reaches a Windows drive through drvfs; it is an ordinary POSIX path.
+ "wsl": (posixpath, "/mnt/d/Models/MyModel"),
+ "macos": (posixpath, "/Users/u/models/MyModel"),
+}
+
+# Cells that are not real products. Kept as invariance checks only -- passing
+# here is NOT a claim that Unsloth supports CUDA or ROCm on macOS.
+_UNREAL_CELLS = {("macos", "nvidia"), ("macos", "rocm")}
+
+
[email protected]("os_name", sorted(_OS_CELLS))
+def test_stem_is_identical_in_every_cell(os_name):
+ flavour, base = _OS_CELLS[os_name]
+ stem = _load_helper()(base)
+ assert stem == "MyModel", f"cell {os_name}/{_GPU_CELL}: {base!r} -> {stem!r}"
+
+
[email protected]("os_name", sorted(_OS_CELLS))
+def test_destination_is_identical_in_every_cell(os_name):
+ """Same stem, same join result, regardless of GPU vendor."""
+ flavour, base = _OS_CELLS[os_name]
+ gguf_dir = (
+ r"C:\Users\u\.unsloth\exports\run_gguf"
+ if flavour is ntpath
+ else "/home/u/.unsloth/exports/run_gguf"
+ )
+ stem = _load_helper()(base)
+ out = flavour.join(gguf_dir, f"{stem}.Q5_K_M.gguf")
+ assert flavour.dirname(out) == gguf_dir, f"cell {os_name}/{_GPU_CELL}: {out!r}"
+ assert flavour.basename(out) == "MyModel.Q5_K_M.gguf"
+
+
+def test_the_gpu_cell_really_is_what_it_claims():
+ """Guard the harness itself: a silently-inert spoof would fake 12 green cells."""
+ if "error" in _GPU_STATE:
+ pytest.skip(f"torch unavailable for cell {_GPU_CELL}: {_GPU_STATE['error']}")
+ if _GPU_CELL == "nvidia":
+ assert _GPU_STATE["cuda"] is True
+ assert not _GPU_STATE["hip"]
+ elif _GPU_CELL == "rocm":
+ assert _GPU_STATE["cuda"] is True
+ assert _GPU_STATE["hip"], "ROCm cell has no torch.version.hip"
+ elif _GPU_CELL == "cpu":
+ assert _GPU_STATE["cuda"] is False
+
+
+def test_the_fix_imports_no_gpu_library():
+ """_model_basename must stay pure: no torch, no accelerator probing."""
+ src = _SAVE_PY.read_text(encoding = "utf-8")
+ fn = next(
+ n
+ for n in ast.parse(src).body
+ if isinstance(n, ast.FunctionDef) and n.name == "_model_basename"
+ )
+ body = ast.get_source_segment(src, fn)
+ for forbidden in ("torch", "cuda", "hip", "device", "unsloth_zoo"):
+ assert forbidden not in body, f"_model_basename references {forbidden!r}"
+ assert not any(
+ isinstance(n, (ast.Import, ast.ImportFrom)) for n in ast.walk(fn)
+ ), "_model_basename must not import anything"
+
+
+def test_unreal_cells_are_declared_not_claimed():
+ """macOS x NVIDIA / macOS x ROCm do not exist; this documents that."""
+ for os_name, gpu in _UNREAL_CELLS:
+ assert os_name in _OS_CELLS and gpu in {"nvidia", "rocm"}
diff --git a/tests/test_gguf_model_basename.py b/tests/test_gguf_model_basename.py
new file mode 100644
index 00000000000..ab6c3fac3dc
--- /dev/null
+++ b/tests/test_gguf_model_basename.py
@@ -0,0 +1,270 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""GGUF filenames must never carry a directory, drive or UNC prefix (#7897).
+
+When a LoRA's base model is a local Windows directory, ``config._name_or_path`` has
+no forward slash, so the old ``split("/")[-1]`` kept the whole path as the model
+name. Joining that onto the output directory relocated the file, because
+``ntpath.join`` discards its first argument when the second carries a drive:
+
+ ntpath.join(r"C:\\exp\\_gguf", r"D:\\M\\X.Q5_K_M.gguf") == r"D:\\M\\X.Q5_K_M.gguf"
+
+The GGUF landed next to the base model and Studio logged ``(none)``.
+
+These run on Linux and still assert the Windows answers, deliberately:
+``os.path.basename`` returns the whole ``D:\\...`` string on POSIX, so a fix built
+on it would pass here while Windows stayed broken.
+"""
+
+from __future__ import annotations
+
+import ast
+import ntpath
+import posixpath
+import re
+from pathlib import Path
+
+import pytest
+
+
+_REPO_ROOT = Path(__file__).resolve().parent.parent
+_SAVE_PY = _REPO_ROOT / "unsloth" / "save.py"
+
+
+def _load_helper():
+ """Exec just ``_model_basename`` out of save.py: save.py cannot be imported
+ without the full ML stack, and the helper is pure string/stat logic. Same ast
+ lift as test_export_capability.py.
+ """
+ src = _SAVE_PY.read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == "_model_basename":
+ namespace: dict = {"os": __import__("os")}
+ exec(compile(ast.Module([node], []), str(_SAVE_PY), "exec"), namespace)
+ return namespace["_model_basename"]
+ raise AssertionError(
+ "unsloth/save.py does not define a module-level _model_basename helper. "
+ "GGUF filenames are still derived with .split('/')[-1], which keeps the "
+ "whole path for Windows base-model directories (issue #7897)."
+ )
+
+
+# Table A: the basename contract.
+# (label, config._name_or_path, expected model_name)
+# Rows marked REGRESSION must be byte-identical to the old .split("/")[-1].
+_TABLE_A = [
+ # -- REGRESSION rows: behaviour must not change -------------------------
+ ("hf_id", "unsloth/Qwen3-8B", "Qwen3-8B"),
+ ("hf_id_nested", "meta-llama/Llama-2-7b-hf", "Llama-2-7b-hf"),
+ ("bare_name", "Qwen3-8B", "Qwen3-8B"),
+ ("posix_abs", "/home/u/models/MyModel", "MyModel"),
+ ("posix_rel", "./models/MyModel", "MyModel"),
+ ("wsl_mount", "/mnt/d/Models/MyModel", "MyModel"),
+ ("win_forward_slashes", "D:/Models/MyModel", "MyModel"),
+ # -- BUG rows: broken today ---------------------------------------------
+ ("posix_trailing_sep", "/home/u/models/MyModel/", "MyModel"),
+ ("win_drive_abs", r"D:\Models\Merged Models\MyModel", "MyModel"),
+ ("win_drive_trailing", "D:\\Models\\MyModel\\", "MyModel"),
+ ("win_mixed_seps", "D:\\Models/Merged Models\\MyModel", "MyModel"),
+ ("unc_share", r"\\server\share\Models\MyModel", "MyModel"),
+ ("unc_extended", r"\\?\UNC\server\share\MyModel", "MyModel"),
+ ("win_extended", r"\\?\D:\Models\MyModel", "MyModel"),
+ ("win_dot_rel", r".\models\MyModel", "MyModel"),
+ ("win_spaces", r"C:\Users\Ada\OneDrive - X\Llama 3.1 8B", "Llama 3.1 8B"),
+ ("win_unicode", "D:\\Модели\\Модель", "Модель"),
+ ("win_short_name", r"C:\Models\MYMODE~1", "MYMODE~1"),
+ ("win_double_dot_name", r"C:\Models\MyModel..v2", "MyModel..v2"),
+ ("repeated_seps", "D:\\Models\\\\MyModel", "MyModel"),
+ # -- degenerate rows: must never yield "" (a hidden .Q4_K_M.gguf) --------
+ ("drive_root", "D:\\", "model"),
+ ("bare_drive", "D:", "model"),
+ ("empty", "", "model"),
+ ("none", None, "model"),
+ ("dot", ".", "model"),
+ ("dotdot", "..", "model"),
+ ("posix_root", "/", "model"),
+]
+
+_REGRESSION_LABELS = {
+ "hf_id",
+ "hf_id_nested",
+ "bare_name",
+ "posix_abs",
+ "posix_rel",
+ "wsl_mount",
+ "win_forward_slashes",
+}
+
+
+ "label, name_or_path, expected",
+ _TABLE_A,
+ ids = [row[0] for row in _TABLE_A],
+)
+def test_model_basename(label, name_or_path, expected):
+ assert _load_helper()(name_or_path) == expected
+
+
+ "label, name_or_path, expected",
+ [row for row in _TABLE_A if row[0] in _REGRESSION_LABELS],
+ ids = [row[0] for row in _TABLE_A if row[0] in _REGRESSION_LABELS],
+)
+def test_working_inputs_are_unchanged(label, name_or_path, expected):
+ """The fix must be inert for every input that already worked."""
+ assert _load_helper()(name_or_path) == name_or_path.split("/")[-1] == expected
+
+
+def test_result_never_starts_with_a_dot():
+ """An empty stem produced hidden files that glob.glob(*.gguf) cannot see."""
+ helper = _load_helper()
+ for _label, name_or_path, _expected in _TABLE_A:
+ stem = helper(name_or_path)
+ assert stem, f"empty stem for {name_or_path!r}"
+ assert not stem.startswith("."), f"hidden GGUF stem {stem!r} for {name_or_path!r}"
+
+
+def test_result_is_never_a_path():
+ """No separator, drive or UNC prefix may survive into a filename."""
+ helper = _load_helper()
+ for _label, name_or_path, _expected in _TABLE_A:
+ stem = helper(name_or_path)
+ assert "/" not in stem and "\\" not in stem, f"{stem!r} from {name_or_path!r}"
+ assert not ntpath.isabs(stem) and not posixpath.isabs(stem)
+ assert ntpath.splitdrive(stem)[0] == "", f"drive survived in {stem!r}"
+
+
+def test_helper_is_idempotent():
+ helper = _load_helper()
+ for _label, name_or_path, _expected in _TABLE_A:
+ once = helper(name_or_path)
+ assert helper(once) == once
+
+
+# The join arithmetic this protects (real ntpath, no mocking).
+
+_GGUF_DIR = r"C:\Users\u\.unsloth\exports\MyModel\_tmp_model_ab12_gguf"
+
+
+ "label, name_or_path, _expected",
+ [row for row in _TABLE_A if row[0] not in _REGRESSION_LABELS],
+ ids = [row[0] for row in _TABLE_A if row[0] not in _REGRESSION_LABELS],
+)
+def test_quantize_output_stays_inside_gguf_directory(label, name_or_path, _expected):
+ """save.py:2073 joins the stem onto gguf_directory. Prove it cannot escape.
+
+ Exact arithmetic from _quantize_one: the unfixed stem silently relocates the
+ output to another drive/UNC share, the fixed stem stays put.
+ """
+ stem = _load_helper()(name_or_path)
+ out = ntpath.join(_GGUF_DIR, f"{stem}.Q5_K_M.gguf")
+ assert (
+ ntpath.dirname(out) == _GGUF_DIR
+ ), f"{name_or_path!r} -> stem {stem!r} -> output escaped to {out!r}"
+ assert ntpath.basename(out) != ".Q5_K_M.gguf"
+
+
+def test_unfixed_derivation_really_did_escape():
+ """Pin the failure mode itself, so nobody 'simplifies' the helper back."""
+ broken = r"D:\Models\Merged Models\MyModel".split("/")[-1]
+ escaped = ntpath.join(_GGUF_DIR, f"{broken}.Q5_K_M.gguf")
+ assert escaped == r"D:\Models\Merged Models\MyModel.Q5_K_M.gguf"
+ assert ntpath.dirname(escaped) != _GGUF_DIR
+
+
+# Source guards.
+
+
+def _gguf_func_src(name: str) -> str:
+ src = _SAVE_PY.read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ return ast.get_source_segment(src, node)
+ raise AssertionError(f"{name} not found in unsloth/save.py")
+
+
+def test_derivation_no_longer_splits_on_forward_slash_only():
+ body = _gguf_func_src("unsloth_save_pretrained_gguf")
+ assert 'split("/")[-1]' not in body, (
+ "unsloth_save_pretrained_gguf still derives the GGUF stem with "
+ "split('/')[-1]; Windows base-model directories keep the whole path."
+ )
+ assert "_model_basename(" in body
+
+
+def test_lora_gguf_path_shares_the_helper():
+ """save.py already had Windows-safe basename logic here; keep the two in sync."""
+ body = _gguf_func_src("_unsloth_save_lora_gguf")
+ assert "_model_basename(" in body
+
+
+def test_helper_is_module_level_and_adds_no_locals_to_the_gguf_entrypoint():
+ """save.py does `arguments = dict(locals())` and splats it into
+ unsloth_generic_save(**arguments). Any NEW local bound before that line
+ becomes an unexpected keyword argument and breaks every GGUF export on
+ every OS, so the helper must live at module level."""
+ src = _SAVE_PY.read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+
+ assert any(
+ isinstance(n, ast.FunctionDef) and n.name == "_model_basename" for n in tree.body
+ ), "_model_basename must be module level, not nested inside the entrypoint"
+
+ body = _gguf_func_src("unsloth_save_pretrained_gguf")
+ fn = ast.parse(body).body[0]
+
+ def _is_locals_snapshot(stmt) -> bool:
+ # `arguments = dict(locals())`
+ if not isinstance(stmt, ast.Assign) or not isinstance(stmt.value, ast.Call):
+ return False
+ call = stmt.value
+ return (
+ isinstance(call.func, ast.Name)
+ and call.func.id == "dict"
+ and len(call.args) == 1
+ and isinstance(call.args[0], ast.Call)
+ and isinstance(call.args[0].func, ast.Name)
+ and call.args[0].func.id == "locals"
+ )
+
+ def _always_exits(stmts) -> bool:
+ """True if this block can never fall through to the snapshot."""
+ for stmt in stmts:
+ if isinstance(stmt, (ast.Return, ast.Raise)):
+ return True
+ if isinstance(stmt, ast.If) and stmt.orelse:
+ if _always_exits(stmt.body) and _always_exits(stmt.orelse):
+ return True
+ return False
+
+ # Locals bound before `arguments = dict(locals())`. Names bound only in a branch
+ # that always returns/raises (the save_method="lora" early exit) never reach it.
+ bound: set[str] = set()
+ saw_snapshot = False
+ for stmt in fn.body:
+ if _is_locals_snapshot(stmt):
+ saw_snapshot = True
+ break
+ if isinstance(stmt, ast.If) and _always_exits(stmt.body) and not stmt.orelse:
+ continue
+ for sub in ast.walk(stmt):
+ if isinstance(sub, ast.Name) and isinstance(sub.ctx, ast.Store):
+ bound.add(sub.id)
+ assert saw_snapshot, (
+ "expected `arguments = dict(locals())` in unsloth_save_pretrained_gguf; "
+ "if that changed, this guard needs updating"
+ )
+
+ # Names deleted from `arguments` before the splat.
+ deleted = set(re.findall(r'del\s+arguments\[[\'"](\w+)[\'"]\]', body))
+
+ params = {a.arg for a in fn.args.args} | {a.arg for a in fn.args.kwonlyargs}
+ leaked = bound - deleted - params
+ assert not leaked, (
+ f"these locals reach unsloth_generic_save(**arguments) as unexpected "
+ f"kwargs and will break every GGUF export: {sorted(leaked)}"
+ )
diff --git a/tests/test_gguf_windows_export_routing.py b/tests/test_gguf_windows_export_routing.py
new file mode 100644
index 00000000000..cec00e2aac9
--- /dev/null
+++ b/tests/test_gguf_windows_export_routing.py
@@ -0,0 +1,219 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""End-to-end routing proof for #7897, run on Linux.
+
+save.py's module-global ``os`` is swapped for a shim whose pure path functions come
+from ``ntpath``, so ``save_to_gguf`` does the exact join arithmetic a Windows host
+would. The assertion is on the ``output_gguf`` reaching ``quantize_gguf``, which is
+where the GGUF escaped the export directory.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import ntpath
+import posixpath
+
+import pytest
+
+# test_gguf_model_basename.py covers the pure basename contract with no deps; this
+# file drives the real save_to_gguf, so it needs the ML stack. Skip cleanly rather
+# than failing collection in a minimal environment.
+save_mod = pytest.importorskip("unsloth.save", reason = "needs torch + unsloth_zoo")
+
+
+# OS shim: pure path ops from ntpath/posixpath, filesystem ops stay real.
+
+_PURE = {
+ "join",
+ "basename",
+ "dirname",
+ "split",
+ "splitdrive",
+ "splitext",
+ "normpath",
+ "normcase",
+ "isabs",
+ "commonpath",
+ "sep",
+ "altsep",
+}
+
+
+class _PathShim:
+ def __init__(self, flavour):
+ self._f = flavour
+
+ def __getattr__(self, name):
+ import os as _os
+ return getattr(self._f if name in _PURE else _os.path, name)
+
+
+class _OsShim:
+ """`os` with a swapped `.path`; makedirs/listdir/remove stay real."""
+
+ def __init__(self, flavour):
+ self.path = _PathShim(flavour)
+
+ def __getattr__(self, name):
+ import os as _os
+ return getattr(_os, name)
+
+
+class _Harness:
+ """convert/quantize mocked, reproducing unsloth_zoo's real output naming."""
+
+ def __init__(self, monkeypatch, tmp_path, flavour):
+ self.tmp_path = tmp_path
+ self.flavour = flavour
+ self.convert_calls = []
+ self.quantize_calls = []
+ self.initial_names = []
+
+ monkeypatch.setattr(save_mod, "check_llama_cpp", lambda: ("llama-quantize", "convert.py"))
+ monkeypatch.setattr(
+ save_mod,
+ "_download_convert_hf_to_gguf",
+ lambda: (str(tmp_path / "convert.py"), {"LlamaForCausalLM"}, set()),
+ )
+ monkeypatch.setattr(save_mod, "use_local_gguf", contextlib.nullcontext)
+ monkeypatch.setattr(save_mod, "convert_to_gguf", self._convert)
+ monkeypatch.setattr(save_mod, "quantize_gguf", self._quantize)
+ monkeypatch.setattr(save_mod, "os", _OsShim(flavour))
+
+ def _scratch(self, virtual_path: str):
+ """Materialise a virtual (possibly Windows) path as one real POSIX file."""
+ safe = virtual_path.replace("\\", "#").replace("/", "#").replace(":", "%")
+ real = self.tmp_path / "artifacts" / safe
+ real.parent.mkdir(parents = True, exist_ok = True)
+ real.write_bytes(b"GGUF")
+ return real
+
+ def _convert(self, **kwargs):
+ self.convert_calls.append(kwargs)
+ model_name = kwargs["model_name"]
+ qtype = kwargs["quantization_type"]
+ if qtype == "None":
+ qtype = kwargs.get("model_dtype", "bf16")
+ # unsloth_zoo/llama_cpp.py:2465 -- the name zoo would build.
+ final = model_name if model_name.endswith(".gguf") else f"{model_name}.{qtype.upper()}.gguf"
+ self.initial_names.append(final)
+ # save.py:2037 requires the returned paths to exist. The escape under test is
+ # at the *quantize* join (model_name + gguf_directory), not this path.
+ return [str(self._scratch(final))], False
+
+ def _quantize(self, input_gguf, output_gguf, quant_type, **kw):
+ self.quantize_calls.append(
+ {"input": input_gguf, "output": output_gguf, "quant": quant_type}
+ )
+ self._scratch(output_gguf)
+ return output_gguf
+
+
+_WINDOWS_BASE = r"D:\Models\Merged Models\MyModel"
+_EXPORT_DIR = r"C:\Users\u\.unsloth\studio\exports\MyModel\_tmp_model_ab12"
+
+
+def _run(
+ monkeypatch,
+ tmp_path,
+ model_name,
+ model_directory,
+ flavour = ntpath,
+ methods = None,
+):
+ harness = _Harness(monkeypatch, tmp_path, flavour)
+ monkeypatch.setattr(save_mod, "shutil", _NoMove(), raising = False)
+ # gguf_directory is a Windows-style string here; os.makedirs is the *real* one,
+ # so chdir into tmp so a literal "C:\..." directory cannot land in the repo.
+ monkeypatch.chdir(tmp_path)
+ save_mod.save_to_gguf(
+ model_name = model_name,
+ model_type = "llama",
+ model_dtype = "bfloat16",
+ model_directory = model_directory,
+ quantization_method = methods or ["q5_k_m"],
+ )
+ return harness
+
+
+class _NoMove:
+ """save_to_gguf relocates initial files with shutil.move, but the sources here are
+ virtual Windows paths that do not exist on POSIX. Neutralise the move."""
+
+ def move(self, src, dst):
+ return dst
+
+ def rmtree(self, *a, **kw):
+ return None
+
+ def copy2(self, *a, **kw):
+ return None
+
+ def which(self, *a, **kw):
+ return None
+
+
+def test_derived_stem_keeps_quantized_gguf_inside_gguf_directory(monkeypatch, tmp_path):
+ """The fixed derivation: output stays under <model_directory>_gguf."""
+ stem = save_mod._model_basename(_WINDOWS_BASE)
+ harness = _run(monkeypatch, tmp_path, stem, _EXPORT_DIR)
+
+ assert harness.quantize_calls, (
+ "no llama-quantize pass ran, so this parametrization cannot detect the "
+ "bug -- a k-quant (not q8_0/f16/bf16) is required"
+ )
+ expected_dir = _EXPORT_DIR + "_gguf"
+ for call in harness.quantize_calls:
+ assert ntpath.dirname(call["output"]) == expected_dir, call["output"]
+ assert not call["output"].startswith("D:"), call["output"]
+
+
+def test_legacy_stem_escaped_to_the_base_model_drive(monkeypatch, tmp_path):
+ """Pin the #7897 failure mode: the pre-fix stem relocated the output to D:."""
+ legacy_stem = _WINDOWS_BASE.split("/")[-1] # the old derivation
+ harness = _run(monkeypatch, tmp_path, legacy_stem, _EXPORT_DIR)
+
+ assert harness.quantize_calls
+ escaped = harness.quantize_calls[0]["output"]
+ assert escaped == r"D:\Models\Merged Models\MyModel.Q5_K_M.gguf"
+ assert ntpath.dirname(escaped) != _EXPORT_DIR + "_gguf"
+
+
+def test_trailing_separator_no_longer_yields_a_hidden_gguf(monkeypatch, tmp_path):
+ """OS-agnostic half of the bug: a trailing sep gave an empty stem."""
+ assert "".join(_WINDOWS_BASE.rsplit("\\", 1)[1:]) == "MyModel"
+ legacy_stem = "/home/u/models/MyModel/".split("/")[-1]
+ assert legacy_stem == "" # the old behaviour
+
+ stem = save_mod._model_basename("/home/u/models/MyModel/")
+ export_dir = str(tmp_path / "exports" / "run")
+ harness = _run(monkeypatch, tmp_path, stem, export_dir, flavour = posixpath)
+
+ assert harness.quantize_calls
+ out = harness.quantize_calls[0]["output"]
+ assert posixpath.basename(out) == "MyModel.Q5_K_M.gguf"
+ assert not posixpath.basename(out).startswith(".")
+ assert posixpath.dirname(out) == export_dir + "_gguf"
+
+
[email protected]("methods", [["q5_k_m"], ["q4_k_m", "q5_k_m"], ["q4_k_m", "q8_0"]])
+def test_multi_quant_all_outputs_stay_inside(monkeypatch, tmp_path, methods):
+ stem = save_mod._model_basename(_WINDOWS_BASE)
+ harness = _run(monkeypatch, tmp_path, stem, _EXPORT_DIR, methods = methods)
+ expected_dir = _EXPORT_DIR + "_gguf"
+ assert harness.quantize_calls
+ for call in harness.quantize_calls:
+ assert ntpath.dirname(call["output"]) == expected_dir, call["output"]
+
+
+def test_posix_paths_route_identically(monkeypatch, tmp_path):
+ """Control arm: the fix must not change POSIX behaviour."""
+ stem = save_mod._model_basename("/home/u/models/MyModel")
+ assert stem == "MyModel"
+ export_dir = str(tmp_path / "exports" / "run")
+ harness = _run(monkeypatch, tmp_path, stem, export_dir, flavour = posixpath)
+ assert harness.quantize_calls
+ for call in harness.quantize_calls:
+ assert posixpath.dirname(call["output"]) == export_dir + "_gguf"
diff --git a/tests/test_gguf_windows_native.py b/tests/test_gguf_windows_native.py
new file mode 100644
index 00000000000..fd8a4e328b3
--- /dev/null
+++ b/tests/test_gguf_windows_native.py
@@ -0,0 +1,125 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Native-Windows proof for #7897. Skipped everywhere else.
+
+The Linux suite simulates Windows by injecting ntpath; this asserts the same
+properties with the real os.path on real NTFS, so the simulation cannot quietly
+diverge from the platform it models. windows-latest runners have a second drive
+letter, which makes the cross-drive case real rather than notional.
+"""
+
+from __future__ import annotations
+
+import ast
+import glob
+import os
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+pytestmark = pytest.mark.skipif(sys.platform != "win32", reason = "native Windows path semantics")
+
+_REPO_ROOT = Path(__file__).resolve().parent.parent
+_SAVE_PY = _REPO_ROOT / "unsloth" / "save.py"
+
+
+def _load_helper():
+ src = _SAVE_PY.read_text(encoding = "utf-8")
+ for node in ast.parse(src).body:
+ if isinstance(node, ast.FunctionDef) and node.name == "_model_basename":
+ ns: dict = {"os": os}
+ exec(compile(ast.Module([node], []), str(_SAVE_PY), "exec"), ns)
+ return ns["_model_basename"]
+ raise AssertionError("unsloth/save.py defines no _model_basename")
+
+
+# Ground truth: the platform behaviours the Linux simulation asserts.
+
+
+def test_join_really_discards_the_prefix_for_a_drive_bearing_component():
+ """The mechanism behind #7897, on the real platform."""
+ assert os.path.join(r"C:\exp\_gguf", r"D:\M\X.Q5_K_M.gguf") == r"D:\M\X.Q5_K_M.gguf"
+ assert os.path.join(r"C:\exp", r"\\server\share\X.gguf") == r"\\server\share\X.gguf"
+ # A rooted-but-driveless component keeps the drive, drops the directory.
+ assert os.path.join(r"C:\exp", r"\Models\X.gguf") == r"C:\Models\X.gguf"
+
+
+def test_glob_really_hides_dot_leading_gguf():
+ """Why the final listing moved off glob.glob."""
+ with tempfile.TemporaryDirectory() as d:
+ Path(d, ".BF16.gguf").write_bytes(b"GGUF")
+ Path(d, "ok.gguf").write_bytes(b"GGUF")
+ assert [os.path.basename(p) for p in glob.glob(os.path.join(d, "*.gguf"))] == ["ok.gguf"]
+ assert sorted(p.name for p in Path(d).glob("*.gguf")) == [".BF16.gguf", "ok.gguf"]
+
+
+def test_posix_basename_would_not_have_fixed_it():
+ """os.path.basename is correct here but wrong on the Linux CI that tests it."""
+ import posixpath
+
+ assert os.path.basename(r"D:\M\MyModel") == "MyModel" # ntpath: fine
+ assert posixpath.basename(r"D:\M\MyModel") == r"D:\M\MyModel" # posix: broken
+
+
+# The fix, on real paths.
+
+
+ "base, expected",
+ [
+ (r"D:\Models\Merged Models\MyModel", "MyModel"),
+ ("D:\\Models\\MyModel\\", "MyModel"),
+ (r"\\?\D:\Models\MyModel", "MyModel"),
+ (r"\\server\share\Models\MyModel", "MyModel"),
+ (r"C:\Users\Ada\OneDrive - X\Llama 3.1 8B", "Llama 3.1 8B"),
+ ("D:\\", "model"),
+ ("D:", "model"),
+ ("unsloth/Qwen3-8B", "Qwen3-8B"),
+ ],
+)
+def test_basename_on_native_windows(base, expected):
+ assert _load_helper()(base) == expected
+
+
+def test_output_stays_on_the_export_drive(tmp_path):
+ """Cross-drive: base model on D:, export on the runner's temp drive."""
+ helper = _load_helper()
+ gguf_dir = str(tmp_path / "run_gguf")
+ os.makedirs(gguf_dir, exist_ok = True)
+
+ stem = helper(r"D:\Models\Merged Models\MyModel")
+ out = os.path.join(gguf_dir, f"{stem}.Q5_K_M.gguf")
+
+ assert os.path.dirname(out) == gguf_dir
+ assert os.path.splitdrive(out)[0].upper() == os.path.splitdrive(gguf_dir)[0].upper()
+
+ Path(out).write_bytes(b"GGUF")
+ assert [p.name for p in Path(gguf_dir).glob("*.gguf")] == ["MyModel.Q5_K_M.gguf"]
+
+
[email protected](not os.path.isdir("D:\\"), reason = "runner has no D: drive")
+def test_real_second_drive_end_to_end():
+ """A real base-model directory on D:, a real export dir on C:."""
+ helper = _load_helper()
+ base_dir = r"D:\Models\Merged Models\MyModel"
+ os.makedirs(base_dir, exist_ok = True)
+
+ with tempfile.TemporaryDirectory() as export_root:
+ gguf_dir = os.path.join(export_root, "_tmp_model_ab12_gguf")
+ os.makedirs(gguf_dir, exist_ok = True)
+
+ out = os.path.join(gguf_dir, f"{helper(base_dir)}.Q5_K_M.gguf")
+ Path(out).write_bytes(b"GGUF")
+
+ # Nothing may be written beside the base model.
+ strays = [
+ os.path.join(root, f)
+ for root, _d, files in os.walk(r"D:\Models")
+ for f in files
+ if f.lower().endswith(".gguf")
+ ]
+ assert strays == [], f"GGUF leaked next to the base model: {strays}"
+ assert os.path.isfile(out)
diff --git a/unsloth/save.py b/unsloth/save.py
index 99afc7db761..ad1fa40648b 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -2863,6 +2863,40 @@ def push_to_ollama(tokenizer, gguf_location, username: str, model_name: str, tag
print("Successfully pushed to ollama")
+def _model_basename(name_or_path, default = "model") -> str:
+ """Leaf name of a model id or path, for use as a GGUF filename stem.
+
+ Strips `\\` as well as `/` on every host: `os.path.basename` returns the whole
+ `D:\\...` string on POSIX. A directory or drive left in the stem makes
+ `os.path.join(gguf_directory, stem)` discard gguf_directory under ntpath, so the
+ GGUF lands next to the base model (#7897); an empty stem gives a hidden
+ `.Q4_K_M.gguf` that `glob.glob` cannot see.
+ """
+ if name_or_path is None:
+ return default
+ try:
+ text = os.fspath(name_or_path)
+ except TypeError:
+ text = str(name_or_path)
+ if not isinstance(text, str) or not text.strip():
+ return default
+
+ # A real directory wins: a POSIX directory name may legally contain a backslash.
+ try:
+ if os.path.isdir(text):
+ base = os.path.basename(os.path.normpath(text))
+ if base and base not in (".", ".."):
+ return base
+ except (OSError, ValueError):
+ pass
+
+ base = text.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]
+ # A bare drive ("D:") or "." would give a drive-relative or hidden output file.
+ if not base or base in (".", "..") or (len(base) == 2 and base[1] == ":"):
+ return default
+ return base
+
+
@_normalize_tied_weights_keys_for_save
def unsloth_save_pretrained_gguf(
self,
@@ -2951,12 +2985,14 @@ def unsloth_save_pretrained_gguf(
_outtype = "f16"
return _unsloth_save_lora_gguf(self, tokenizer, save_directory, outtype = _outtype)
+ # base_model_name keeps the full id for create_ollama_modelfile's mapper lookup;
+ # only the filename stem is trimmed.
+ base_model_name = getattr(getattr(self, "config", None), "_name_or_path", None)
try:
- base_model_name = get_model_name(self.config._name_or_path, load_in_4bit = False)
- model_name = base_model_name.split("/")[-1]
- except:
- base_model_name = self.config._name_or_path
- model_name = base_model_name.split("/")[-1]
+ base_model_name = get_model_name(base_model_name, load_in_4bit = False)
+ except Exception:
+ pass
+ model_name = _model_basename(base_model_name)
# Check if push_to_hub is requested
if push_to_hub:
@@ -3711,13 +3747,7 @@ def _unsloth_save_lora_gguf(
base_model_id = get_model_name(base_model_id, load_in_4bit = False)
except Exception:
pass
- # Windows-safe basename (handles both C:\... and / separators).
- if os.path.isdir(base_model_id):
- model_name = os.path.basename(os.path.normpath(base_model_id))
- else:
- model_name = base_model_id.replace("\\", "/").rstrip("/").split("/")[-1]
- if not model_name:
- model_name = "model"
+ model_name = _model_basename(base_model_id)
# Save the adapter; for a hub push use an isolated temp dir, else save_directory itself.
if push_to_hub: