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: stop converting the model twice when exporting GGUF to the Hub (#10317)
Nilay7b1d8edc9275
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 9827251e40d..61ac0fcb4c5 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -3,6 +3,7 @@"""Export backend - exports models in various formats."""+import globimport jsonimport structlogimport tempfile@@ -414,6 +415,48 @@ This {model_type} model was trained 2x faster with [Unsloth](https://github.com/"""+# Both llama.cpp spellings: the Hub filters on the exact string, and upstream's add_tags is a no-op.+GGUF_MODEL_CARD = """---+tags:+- gguf+- llama.cpp+- llama-cpp+- unsloth{vlm_tag}+---++# {name} : GGUF++This model was converted to GGUF format using [Unsloth](https://github.com/unslothai/unsloth).++**Example usage**:+- For text only LLMs: `llama-cli -hf {repo_id} --jinja`+- For multimodal models: `llama-mtmd-cli -hf {repo_id} --jinja`++## Available model files:+{files}+"""+++def _ensure_hub_repo_private(hf_api, repo_id):+ """Tighten an existing repo to private: create_repo sets `private` only at creation."""+ try:+ hf_api.update_repo_settings(repo_id = repo_id, private = True, repo_type = "model")+ return+ except Exception as exception:+ try:+ info = hf_api.repo_info(repo_id = repo_id, repo_type = "model")+ if bool(getattr(info, "private", False)):+ return+ except Exception:+ pass+ raise RuntimeError(+ f"private=True was requested but {repo_id!r} could not be confirmed private "+ "(the token likely lacks `write:repo_settings`, or the repository belongs to "+ "someone else). Refusing to upload rather than publish the GGUF files to a "+ "public repository."+ ) from exception++class ExportBackend:"""Handles model export operations"""@@ -1136,7 +1179,7 @@ class ExportBackend:shard_hooks = []if save_directory:shard_hooks.append(self.current_model.save_pretrained_gguf)- if push_to_hub:+ elif push_to_hub:shard_hooks.append(self.current_model.push_to_hub_gguf)if gguf_shard_size is not None and not all(_gguf_shard_export_supported(hook) for hook in shard_hooks@@ -1159,6 +1202,11 @@ class ExportBackend:)output_path: Optional[str] = None+ exported_ggufs: List[str] = []+ exported_modelfile = False+ exported_modelfile_bytes: Optional[bytes] = None+ exported_is_vlm = False+ exported_config: Optional[bytes] = Nonetry:# Normalize to a lowercased list so multiple quants come from one model load.if isinstance(quantization_method, (list, tuple)):@@ -1235,6 +1283,12 @@ class ExportBackend:f"GGUF conversion produced a symlink, refusing to relocate it: {src}")dest = os.path.join(abs_save_dir, src.name)+ if os.path.isdir(dest):+ # move would nest the file, and the allow-list would match neither.+ raise RuntimeError(+ f"Cannot relocate {src.name}: a directory of that name is "+ f"already in {abs_save_dir}"+ )shutil.move(str(src), dest)relocated_ggufs.append(dest)logger.info(f"Relocated GGUF: {src.name} → {abs_save_dir}/")@@ -1243,6 +1297,22 @@ class ExportBackend:"GGUF conversion produced no files: no .gguf outputs for "f"{abs_save_dir}")+ exported_ggufs = [str(f) for f in drop_appledouble_metadata(relocated_ggufs)]+ if not exported_ggufs:+ # final_ggufs below would pass on an earlier export's .gguf left here.+ raise RuntimeError(+ "GGUF conversion produced only AppleDouble metadata companions "+ f"and no usable .gguf file for {abs_save_dir}"+ )+ exported_is_vlm = bool(+ reported.get("is_vlm", getattr(self, "is_vision", False))+ )+ # In memory: the temp root goes, and a config.json here reads as a checkpoint.+ merged_config = (+ Path(reported.get("save_directory") or _model_tmp) / "config.json"+ )+ if merged_config.is_file():+ exported_config = merged_config.read_bytes()if modelfiles:modelfile = sorted(modelfiles)[0]@@ -1251,15 +1321,24 @@ class ExportBackend:"GGUF conversion produced a symlinked Modelfile, "f"refusing to relocate it: {modelfile}")- # Optional artifact: a locked or read-only destination must not fail an export whose GGUFs all- # landed.- # Optional artifact: unsloth generates it best-effort, so a locked or read-only- # destination must not fail an export whose GGUFs all landed.+ # Optional: a blocked destination publishes from memory, never fails.+ modelfile_dest = os.path.join(abs_save_dir, "Modelfile")try:- shutil.move(str(modelfile), os.path.join(abs_save_dir, "Modelfile"))+ if os.path.isdir(modelfile_dest):+ raise OSError(+ f"a directory named Modelfile is already in {abs_save_dir}"+ )+ shutil.move(str(modelfile), modelfile_dest)+ exported_modelfile = Truelogger.info(f"Relocated Modelfile → {abs_save_dir}/")except OSError as exception:logger.warning(f"Could not relocate the Modelfile: {exception}")+ try:+ exported_modelfile_bytes = modelfile.read_bytes()+ except OSError as read_exception:+ logger.warning(+ f"Could not read the Modelfile to upload it: {read_exception}"+ )finally:# The imatrix is an input, so counting it would retain the merged checkpoint on every such export.unrelocated = []@@ -1314,15 +1393,63 @@ class ExportBackend:logger.info(f"Pushing GGUF model to Hub: {repo_id}")- self.current_model.push_to_hub_gguf(- repo_id,- self.current_tokenizer,- quantization_method = quant_method,- token = hf_token,- private = private,- **imatrix_kw,- **shard_kw,- )+ if output_path and Path(output_path).is_dir():+ # These are already built; push_to_hub_gguf would convert the model again.+ hf_api = HfApi(token = hf_token)+ repo_url = hf_api.create_repo(repo_id, private = private, exist_ok = True)+ repo_id = getattr(repo_url, "repo_id", repo_id)+ if private:+ _ensure_hub_repo_private(hf_api, repo_id)+ # Allow-list, not the folder; glob.escape keeps "model[v2].gguf" a literal.+ hf_api.upload_folder(+ folder_path = output_path,+ repo_id = repo_id,+ repo_type = "model",+ allow_patterns = [+ *(glob.escape(os.path.basename(f)) for f in exported_ggufs),+ *(["Modelfile"] if exported_modelfile else []),+ ],+ )+ if exported_config is not None:+ hf_api.upload_file(+ path_or_fileobj = exported_config,+ path_in_repo = "config.json",+ repo_id = repo_id,+ repo_type = "model",+ commit_message = "Unsloth config.json",+ )+ if exported_modelfile_bytes is not None:+ hf_api.upload_file(+ path_or_fileobj = exported_modelfile_bytes,+ path_in_repo = "Modelfile",+ repo_id = repo_id,+ repo_type = "model",+ commit_message = "Unsloth Ollama Modelfile",+ )+ # Last (advertises the files), best-effort: RepoCard hardcodes huggingface.co.+ try:+ ModelCard(+ GGUF_MODEL_CARD.format(+ name = repo_id.split("/")[-1],+ repo_id = repo_id,+ vlm_tag = "\n- vision-language-model" if exported_is_vlm else "",+ files = "\n".join(+ f"- `{os.path.basename(f)}`" for f in exported_ggufs+ ),+ )+ ).push_to_hub(repo_id, token = hf_token, commit_message = "Unsloth Model Card")+ except Exception as exception:+ logger.warning(f"Could not publish the model card: {exception}")+ else:+ self.current_model.push_to_hub_gguf(+ repo_id,+ self.current_tokenizer,+ quantization_method = quant_method,+ token = hf_token,+ private = private,+ **imatrix_kw,+ **shard_kw,+ )logger.info(f"GGUF model pushed successfully to {repo_id}")return (@@ -1336,6 +1463,13 @@ class ExportBackend:import tracebacklogger.error(traceback.format_exc())+ if output_path:+ # Only the Hub leg can raise once output_path is set, so the files are on disk.+ return (+ False,+ f"GGUF files were saved to {output_path}, but the Hub upload failed: {e}",+ output_path,+ )return False, f"GGUF export failed: {str(e)}", Nonedef export_lora_adapter(diff --git a/studio/backend/tests/test_export_gguf_discovery.py b/studio/backend/tests/test_export_gguf_discovery.pyindex f1098667ae1..e09d8349258 100644--- a/studio/backend/tests/test_export_gguf_discovery.py+++ b/studio/backend/tests/test_export_gguf_discovery.py@@ -57,6 +57,74 @@ def _backend(return export_mod, backend, save_dir, cwd+def _hub_doubles(export_mod, monkeypatch, calls: dict):+ class _RepoUrl(str):+ repo_id = "org/model"++ class _HfApi:+ def __init__(self, token = None):+ calls["token"] = token++ def create_repo(+ self,+ repo_id,+ private = False,+ exist_ok = False,+ ):+ calls["repo"] = {"repo_id": repo_id, "private": private}+ return _RepoUrl("https://huggingface.co/org/model")++ def update_repo_settings(+ self,+ repo_id,+ private = None,+ repo_type = None,+ ):+ calls["visibility"] = {"repo_id": repo_id, "private": private}++ def repo_info(+ self,+ repo_id,+ repo_type = None,+ ):+ return None++ def upload_file(+ self,+ path_or_fileobj,+ path_in_repo,+ repo_id,+ repo_type = None,+ commit_message = None,+ ):+ calls[path_in_repo] = path_or_fileobj++ def upload_folder(+ self,+ folder_path,+ repo_id,+ repo_type,+ allow_patterns = None,+ ignore_patterns = None,+ ):+ calls["upload"] = folder_path++ class _ModelCard:+ def __init__(self, content):+ calls["card"] = content++ def push_to_hub(+ self,+ repo_id,+ token = None,+ commit_message = None,+ ):+ calls["card_repo"] = repo_id++ monkeypatch.setattr(export_mod, "HfApi", _HfApi)+ monkeypatch.setattr(export_mod, "ModelCard", _ModelCard)++def _gguf(path: Path, payload: bytes = b"GGUF") -> Path:path.parent.mkdir(parents = True, exist_ok = True)path.write_bytes(payload)@@ -487,12 +555,15 @@ def test_local_gguf_export_forwards_the_token_for_the_upstream_imatrix(monkeypatassert calls["save"] == {"imatrix_file": True, "token": "hf_secret"}-def test_hub_push_with_an_imatrix_passes_the_token_exactly_once(monkeypatch, tmp_path):- """push_to_hub_gguf already names token=, so the local extra must not reach it as well."""+def test_hub_push_uploads_the_local_export_instead_of_converting_again(monkeypatch, tmp_path):+ """push_to_hub_gguf would re-run the whole conversion into the system temp dir."""calls: dict = {}- _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(True, calls))+ export_mod, backend, save_dir, _cwd = _backend(+ monkeypatch, tmp_path, _imatrix_model(True, calls)+ )+ _hub_doubles(export_mod, monkeypatch, calls)- success, message, _p = backend.export_gguf(+ success, message, output_path = backend.export_gguf(str(save_dir),"iq2_xxs",push_to_hub = True,@@ -502,20 +573,20 @@ def test_hub_push_with_an_imatrix_passes_the_token_exactly_once(monkeypatch, tmp)assert success is True, message- assert calls["push"] == {- "repo_id": "org/model",- "token": "hf_secret",- "imatrix_file": True,- "private": False,- }+ assert "push" not in calls+ assert calls["token"] == "hf_secret"+ assert calls["upload"] == output_path == str(save_dir.resolve())@pytest.mark.parametrize("imatrix_file", [None, False, True])@pytest.mark.parametrize("private", [True, False])def test_hub_push_gguf_forwards_private_flag(monkeypatch, tmp_path, imatrix_file, private):- """push_to_hub_gguf receives the requested private flag for both standard and imatrix exports."""+ """The created repo receives the requested private flag for standard and imatrix exports."""calls: dict = {}- _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(True, calls))+ export_mod, backend, save_dir, _cwd = _backend(+ monkeypatch, tmp_path, _imatrix_model(True, calls)+ )+ _hub_doubles(export_mod, monkeypatch, calls)success, message, _p = backend.export_gguf(str(save_dir),@@ -528,7 +599,7 @@ def test_hub_push_gguf_forwards_private_flag(monkeypatch, tmp_path, imatrix_file)assert success is True, message- assert calls["push"]["private"] is private+ assert calls["repo"] == {"repo_id": "org/model", "private": private}def test_gguf_export_without_an_imatrix_does_not_forward_the_token(monkeypatch, tmp_path):diff --git a/studio/backend/tests/test_export_gguf_hub_upload.py b/studio/backend/tests/test_export_gguf_hub_upload.pynew file mode 100644index 00000000000..c3a00d41a4a--- /dev/null+++ b/studio/backend/tests/test_export_gguf_hub_upload.py@@ -0,0 +1,1144 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import importlib.util+import os+import types+from fnmatch import fnmatchcase+from pathlib import Path++import pytest+++# "*" is a reserved character in a Windows filename, so only POSIX can hold one.+_STAR_IN_NAME_IS_LEGAL = os.name != "nt"+++_HELPERS_SPEC = importlib.util.spec_from_file_location(+ "export_gguf_hub_upload_helpers",+ Path(__file__).with_name("test_export_absolute_paths.py"),+)+assert _HELPERS_SPEC is not None and _HELPERS_SPEC.loader is not None+_HELPERS = importlib.util.module_from_spec(_HELPERS_SPEC)+_HELPERS_SPEC.loader.exec_module(_HELPERS)+_install_export_backend_stubs = _HELPERS._install_export_backend_stubs+_load_module = _HELPERS._load_module+++class _RepoUrl(str):+ repo_id = "owner/model"+++def _hub_doubles(calls, seen):+ class _HfApi:+ def __init__(self, token = None):+ seen["token"] = token++ def create_repo(+ self,+ repo_id,+ private = False,+ exist_ok = False,+ ):+ calls.append("create_repo")+ seen["repo"] = {"repo_id": repo_id, "private": private, "exist_ok": exist_ok}+ return _RepoUrl("https://huggingface.co/owner/model")++ def update_repo_settings(+ self,+ repo_id,+ private = None,+ repo_type = None,+ ):+ calls.append("update_repo_settings")+ seen["visibility"] = {"repo_id": repo_id, "private": private}++ def repo_info(+ self,+ repo_id,+ repo_type = None,+ ):+ calls.append("repo_info")+ return seen.get("repo_info_result")++ def upload_file(+ self,+ path_or_fileobj,+ path_in_repo,+ repo_id,+ repo_type = None,+ commit_message = None,+ ):+ calls.append(f"upload_file:{path_in_repo}")+ seen[path_in_repo] = path_or_fileobj++ def upload_folder(+ self,+ folder_path,+ repo_id,+ repo_type,+ allow_patterns = None,+ ignore_patterns = None,+ ):+ calls.append("upload_folder")+ seen["folder"] = folder_path+ root = Path(folder_path)+ paths = [p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()]+ if allow_patterns is not None:+ paths = [+ p for p in paths if any(fnmatchcase(p, pattern) for pattern in allow_patterns)+ ]+ for pattern in ignore_patterns or ():+ paths = [p for p in paths if not fnmatchcase(p, pattern)]+ seen["uploaded"] = sorted(paths)++ class _ModelCard:+ def __init__(self, content):+ seen["card"] = content++ def push_to_hub(+ self,+ repo_id,+ token = None,+ commit_message = None,+ ):+ calls.append("model_card")+ seen["card_repo"] = repo_id++ return _HfApi, _ModelCard+++def test_gguf_hub_export_uploads_the_built_files_instead_of_reconverting(tmp_path, monkeypatch):+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_backend",+ "core/export/export.py",+ monkeypatch,+ )++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ calls.append("convert")+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")+ (output / "Modelfile").write_text("FROM model.Q4_K_M.gguf")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, output_path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = True,+ )++ assert success is True, message+ assert calls == [+ "convert",+ "create_repo",+ "update_repo_settings",+ "upload_folder",+ "model_card",+ ]+ assert seen["folder"] == output_path+ assert seen["repo"] == {"repo_id": "owner/model", "private": True, "exist_ok": True}+ assert seen["visibility"] == {"repo_id": "owner/model", "private": True}+ assert "model.Q4_K_M.gguf" in seen["uploaded"]+ assert "Modelfile" in seen["uploaded"]+ assert "export_metadata.json" not in seen["uploaded"]+ assert Path(output_path, "export_metadata.json").is_file()+ assert "`model.Q4_K_M.gguf`" in seen["card"]+ assert seen["card_repo"] == "owner/model"+++def test_gguf_hub_export_uploads_only_the_export_artifacts(tmp_path, monkeypatch):+ """The save directory is user-chosen, so its other contents must stay off the Hub."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_scoped_backend",+ "core/export/export.py",+ monkeypatch,+ )++ save_dir = tmp_path / "picked-in-the-folder-browser"+ save_dir.mkdir()+ (save_dir / "notes.txt").write_text("unrelated")+ (save_dir / "dataset.jsonl").write_text('{"a": 1}')+ leftover = save_dir / "_tmp_model_earlier" / "model"+ leftover.mkdir(parents = True)+ (leftover / "model-00001-of-00002.safetensors").write_bytes(b"weights")++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ calls.append("convert")+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")+ (output / "Modelfile").write_text("FROM model.Q4_K_M.gguf")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.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",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["uploaded"] == ["Modelfile", "model.Q4_K_M.gguf"]+ assert (Path(output_path) / "notes.txt").is_file()+ assert (Path(output_path) / "dataset.jsonl").is_file()+ assert (leftover / "model-00001-of-00002.safetensors").is_file()+++def test_gguf_hub_export_allow_list_treats_gguf_names_literally(tmp_path, monkeypatch):+ """A glob character in the model name must not skip its file or match another."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_glob_backend",+ "core/export/export.py",+ monkeypatch,+ )++ save_dir = tmp_path / "llama-3[8b]"+ save_dir.mkdir()+ (save_dir / "a-previous-quant.gguf").write_bytes(b"GGUF")++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ calls.append("convert")+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ if _STAR_IN_NAME_IS_LEGAL:+ (output / "a*.gguf").write_bytes(b"GGUF")+ (output / "llama-3[8b].Q4_K_M.gguf").write_bytes(b"GGUF")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, _path = backend.export_gguf(+ str(save_dir),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ expected = ["llama-3[8b].Q4_K_M.gguf"]+ if _STAR_IN_NAME_IS_LEGAL:+ expected = ["a*.gguf"] + expected+ assert seen["uploaded"] == expected+++def test_gguf_hub_export_skips_an_earlier_export_left_in_the_folder(tmp_path, monkeypatch):+ """Only this run's GGUFs are published, even when the folder holds an older one."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_stale_backend",+ "core/export/export.py",+ monkeypatch,+ )++ save_dir = tmp_path / "shared-export-folder"+ save_dir.mkdir()+ (save_dir / "some-other-model.Q8_0.gguf").write_bytes(b"GGUF")++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ merged = Path(model_save_path)+ merged.mkdir(parents = True)+ (merged / "config.json").write_text('{"model_type": "llama"}')+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")+ (output / "Modelfile").write_text("FROM model.Q4_K_M.gguf")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.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",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["uploaded"] == ["Modelfile", "model.Q4_K_M.gguf"]+ assert "some-other-model.Q8_0.gguf" not in seen["card"]+ assert (Path(output_path) / "some-other-model.Q8_0.gguf").is_file()+ assert seen["config.json"] == b'{"model_type": "llama"}'+ assert not (Path(output_path) / "config.json").exists()+ assert calls.index("model_card") > calls.index("upload_folder")+++def test_gguf_hub_export_leaves_a_stale_modelfile_behind(tmp_path, monkeypatch):+ """A Modelfile from an earlier export points at another model; only a fresh one ships."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_stale_modelfile_backend",+ "core/export/export.py",+ monkeypatch,+ )++ save_dir = tmp_path / "shared-export-folder"+ save_dir.mkdir()+ (save_dir / "Modelfile").write_text("FROM some-other-model.Q8_0.gguf")++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.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",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["uploaded"] == ["model.Q4_K_M.gguf"]+ assert (Path(output_path) / "Modelfile").is_file()+++def test_gguf_hub_export_does_not_publish_appledouble_companions(tmp_path, monkeypatch):+ """A ._ companion beside a GGUF is Finder metadata, not a model file."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_appledouble_backend",+ "core/export/export.py",+ monkeypatch,+ )++ save_dir = tmp_path / "export"+ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")+ (output / "._model.Q4_K_M.gguf").write_bytes(b"\x00\x05\x16\x07")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, _path = backend.export_gguf(+ str(save_dir),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["uploaded"] == ["model.Q4_K_M.gguf"]+ assert "._model.Q4_K_M.gguf" not in seen["card"]++[email protected]("is_vlm", [True, False])+def test_gguf_hub_export_card_carries_the_vlm_tag(tmp_path, monkeypatch, is_vlm):+ """The Hub filters on vision-language-model, and only the exporter knows."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ f"test_export_gguf_hub_upload_vlm_{is_vlm}_backend",+ "core/export/export.py",+ monkeypatch,+ )++ save_dir = tmp_path / "export"+ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ gguf = output / "model.Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")+ return {"gguf_files": [str(gguf)], "is_vlm": is_vlm}++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, _path = backend.export_gguf(+ str(save_dir),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert ("- vision-language-model" in seen["card"]) is is_vlm+ assert seen["card"].startswith("---\ntags:\n")+ assert (+ seen["card"]+ .split("---")[1]+ .strip()+ .endswith("vision-language-model" if is_vlm else "unsloth")+ )+ tags = [line[2:] for line in seen["card"].split("---")[1].strip().splitlines()[1:]]+ assert "llama.cpp" in tags+ assert "llama-cpp" in tags+++def _visibility_backend(+ tmp_path,+ monkeypatch,+ name,+ gguf_names = ("model.Q4_K_M.gguf",),+):+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(name, "core/export/export.py", monkeypatch)++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ calls.append("convert")+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ produced = []+ for gguf_name in gguf_names:+ gguf = output / gguf_name+ gguf.write_bytes(b"\x00\x05\x16\x07" if gguf_name.startswith("._") else b"GGUF")+ produced.append(str(gguf))+ return {"gguf_files": produced}++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None+ return export_module, backend, calls, seen+++def test_gguf_hub_export_makes_an_existing_repo_private_before_uploading(tmp_path, monkeypatch):+ """create_repo ignores private on an existing repo, so a "private" export would land public."""+ _module, backend, calls, seen = _visibility_backend(+ tmp_path, monkeypatch, "test_export_gguf_hub_upload_visibility_backend"+ )++ success, message, _path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = True,+ )++ assert success is True, message+ assert seen["visibility"] == {"repo_id": "owner/model", "private": True}+ assert calls.index("update_repo_settings") < calls.index("upload_folder")+++def test_gguf_hub_export_refuses_to_upload_when_privacy_cannot_be_confirmed(tmp_path, monkeypatch):+ """A private=True export must fail rather than publish to a repo it cannot close."""+ module, backend, calls, seen = _visibility_backend(+ tmp_path, monkeypatch, "test_export_gguf_hub_upload_visibility_denied_backend"+ )++ def _denied(+ self,+ repo_id,+ private = None,+ repo_type = None,+ ):+ raise RuntimeError("403 Forbidden: write:repo_settings missing")++ monkeypatch.setattr(module.HfApi, "update_repo_settings", _denied)+ seen["repo_info_result"] = types.SimpleNamespace(private = False)++ success, message, output_path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = True,+ )++ assert success is False+ assert "could not be confirmed private" in message+ assert "upload_folder" not in calls+ assert output_path is not None+ assert Path(output_path, "model.Q4_K_M.gguf").is_file()+++def test_gguf_hub_export_uploads_when_the_repo_is_already_private(tmp_path, monkeypatch):+ """A token without write:repo_settings still works against an already-private repo."""+ module, backend, calls, seen = _visibility_backend(+ tmp_path, monkeypatch, "test_export_gguf_hub_upload_visibility_ok_backend"+ )++ def _denied(+ self,+ repo_id,+ private = None,+ repo_type = None,+ ):+ raise RuntimeError("403 Forbidden: write:repo_settings missing")++ monkeypatch.setattr(module.HfApi, "update_repo_settings", _denied)+ seen["repo_info_result"] = types.SimpleNamespace(private = True)++ success, message, _path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = True,+ )++ assert success is True, message+ assert seen["uploaded"] == ["model.Q4_K_M.gguf"]+++def test_gguf_hub_export_leaves_an_existing_private_repo_alone(tmp_path, monkeypatch):+ """private=False only means "do not create it private", never "publish this repo"."""+ _module, backend, calls, seen = _visibility_backend(+ tmp_path, monkeypatch, "test_export_gguf_hub_upload_visibility_public_backend"+ )++ success, message, _path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert "update_repo_settings" not in calls+ assert "visibility" not in seen+++def test_gguf_hub_export_survives_a_model_card_failure(tmp_path, monkeypatch):+ """The GGUFs are already committed by then, so losing the card must not fail the export."""+ module, backend, calls, seen = _visibility_backend(+ tmp_path, monkeypatch, "test_export_gguf_hub_upload_card_fails_backend"+ )++ def _boom(+ self,+ repo_id,+ token = None,+ commit_message = None,+ ):+ raise RuntimeError("connection refused: api/validate-yaml")++ monkeypatch.setattr(module.ModelCard, "push_to_hub", _boom)++ success, message, output_path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["uploaded"] == ["model.Q4_K_M.gguf"]+ assert output_path is not None+++def test_gguf_hub_export_reports_the_local_path_when_the_upload_fails(tmp_path, monkeypatch):+ """A failed upload must not read as "re-run the hour-long conversion"."""+ module, backend, calls, seen = _visibility_backend(+ tmp_path, monkeypatch, "test_export_gguf_hub_upload_upload_fails_backend"+ )++ def _boom(+ self,+ folder_path,+ repo_id,+ repo_type,+ allow_patterns = None,+ ignore_patterns = None,+ ):+ raise RuntimeError("504 Gateway Timeout")++ monkeypatch.setattr(module.HfApi, "upload_folder", _boom)++ success, message, output_path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is False+ assert "504 Gateway Timeout" in message+ assert "saved to" in message+ assert output_path is not None+ assert Path(output_path, "model.Q4_K_M.gguf").is_file()+++def test_gguf_hub_export_fails_when_only_appledouble_companions_were_produced(+ tmp_path, monkeypatch+):+ """A run that produced only Finder metadata has produced nothing publishable."""+ save_dir = tmp_path / "export"+ save_dir.mkdir(parents = True)+ (save_dir / "some-other-model.Q8_0.gguf").write_bytes(b"GGUF")++ _module, backend, calls, seen = _visibility_backend(+ tmp_path,+ monkeypatch,+ "test_export_gguf_hub_upload_only_appledouble_backend",+ gguf_names = ("._model.Q4_K_M.gguf",),+ )++ success, message, _path = backend.export_gguf(+ str(save_dir),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is False+ assert "AppleDouble" in message+ assert "upload_folder" not in calls+ assert (save_dir / "some-other-model.Q8_0.gguf").is_file()+++def test_gguf_hub_export_uses_the_canonical_repo_id_the_hub_returns(tmp_path, monkeypatch):+ """The card must use the Hub-resolved repo id, else it advertises `llama-cli -hf model-gguf`."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_canonical_backend", "core/export/export.py", monkeypatch+ )++ calls: list[str] = []+ seen: dict = {}++ class _CanonicalRepoUrl(str):+ repo_id = "resolved-owner/model-gguf"++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)++ def _create_repo(+ self,+ repo_id,+ private = False,+ exist_ok = False,+ ):+ calls.append("create_repo")+ seen["repo"] = {"repo_id": repo_id, "private": private, "exist_ok": exist_ok}+ return _CanonicalRepoUrl("https://huggingface.co/resolved-owner/model-gguf")++ hf_api.create_repo = _create_repo+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, _path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "model-gguf",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["repo"]["repo_id"] == "model-gguf"+ assert seen["card_repo"] == "resolved-owner/model-gguf"+ assert "# model-gguf : GGUF" in seen["card"]+ assert "llama-cli -hf resolved-owner/model-gguf --jinja" in seen["card"]+ assert "llama-mtmd-cli -hf resolved-owner/model-gguf --jinja" in seen["card"]+++def test_gguf_hub_export_reads_config_from_the_directory_the_exporter_reports(+ tmp_path, monkeypatch+):+ """The merged checkpoint is not always under our temp root; unsloth reports where it went."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_reported_dir_backend", "core/export/export.py", monkeypatch+ )++ elsewhere = tmp_path / "somewhere-else"+ elsewhere.mkdir()+ (elsewhere / "config.json").write_bytes(b'{"model_type": "qwen2"}')++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ gguf = output / "model.Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")+ return {"gguf_files": [str(gguf)], "save_directory": str(elsewhere)}++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, output_path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["config.json"] == b'{"model_type": "qwen2"}'+ assert not Path(output_path, "config.json").exists()+++def test_gguf_hub_export_uploads_a_modelfile_it_could_not_place_locally(tmp_path, monkeypatch):+ """A read-only destination must not silently drop an artifact this run produced."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_modelfile_move_fails_backend",+ "core/export/export.py",+ monkeypatch,+ )++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")+ # write_bytes, not write_text: text mode turns "\n" into "\r\n" on Windows.+ (output / "Modelfile").write_bytes(b"FROM ./model.Q4_K_M.gguf\n")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ real_move = export_module.shutil.move++ def _refuse_the_modelfile(src, dst, *args, **kwargs):+ if Path(str(dst)).name == "Modelfile":+ raise OSError("read-only file system")+ return real_move(src, dst, *args, **kwargs)++ monkeypatch.setattr(export_module.shutil, "move", _refuse_the_modelfile)++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, output_path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert not Path(output_path, "Modelfile").exists()+ assert "Modelfile" not in seen["uploaded"]+ assert seen["Modelfile"] == b"FROM ./model.Q4_K_M.gguf\n"+++def test_push_only_gguf_export_still_delegates_to_push_to_hub_gguf(tmp_path, monkeypatch):+ """Nothing built to upload, so push_to_hub_gguf stands and must get the token exactly once."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_push_only_backend", "core/export/export.py", monkeypatch+ )++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(+ self,+ model_save_path,+ tokenizer,+ quantization_method,+ imatrix_file = None,+ token = None,+ gguf_shard_size = None,+ ):+ calls.append("save_pretrained_gguf")++ def push_to_hub_gguf(+ self,+ repo_id,+ tokenizer,+ quantization_method = None,+ token = None,+ private = None,+ imatrix_file = None,+ gguf_shard_size = None,+ ):+ calls.append("push_to_hub_gguf")+ seen["push"] = {+ "repo_id": repo_id,+ "quantization_method": quantization_method,+ "token": token,+ "private": private,+ "imatrix_file": imatrix_file,+ "gguf_shard_size": gguf_shard_size,+ }++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, output_path = backend.export_gguf(+ "",+ "iq2_xxs",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = True,+ imatrix_file = True,+ gguf_shard_size = "512MB",+ )++ assert success is True, message+ assert output_path is None+ assert "save_pretrained_gguf" not in calls+ assert "upload_folder" not in calls+ assert calls == ["push_to_hub_gguf"]+ assert seen["push"] == {+ "repo_id": "owner/model",+ "quantization_method": "iq2_xxs",+ "token": "token",+ "private": True,+ "imatrix_file": True,+ "gguf_shard_size": "512MB",+ }++[email protected]("is_vision", [True, False])+def test_gguf_hub_export_falls_back_to_studios_own_vlm_detection(tmp_path, monkeypatch, is_vision):+ """The MLX binding returns None, so without a fallback vision exports publish untagged."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ f"test_export_gguf_hub_upload_vlm_fallback_{is_vision}_backend",+ "core/export/export.py",+ monkeypatch,+ )++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")+ return None++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None+ backend.is_vision = is_vision++ success, message, _path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert ("- vision-language-model" in seen["card"]) is is_vision+++def test_gguf_hub_export_trusts_the_exporter_over_studios_guess(tmp_path, monkeypatch):+ """A CUDA exporter that reports is_vlm=False wins, even if Studio loaded it as vision."""+ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_vlm_reported_wins_backend",+ "core/export/export.py",+ monkeypatch,+ )++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ gguf = output / "model.Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")+ return {"gguf_files": [str(gguf)], "is_vlm": False}++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.ExportBackend)+ backend.current_model = Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None+ backend.is_vision = True++ success, message, _path = backend.export_gguf(+ str(tmp_path / "export"),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert "- vision-language-model" not in seen["card"]+++def test_gguf_hub_export_rejects_a_directory_where_a_gguf_should_land(tmp_path, monkeypatch):+ """shutil.move would put the file inside it and the allow-list would match nothing."""+ save_dir = tmp_path / "export"+ save_dir.mkdir(parents = True)+ (save_dir / "model.Q4_K_M.gguf").mkdir()+ (save_dir / "an-earlier-export.Q8_0.gguf").write_bytes(b"GGUF")++ _module, backend, calls, seen = _visibility_backend(+ tmp_path, monkeypatch, "test_export_gguf_hub_upload_dir_collision_backend"+ )++ success, message, _path = backend.export_gguf(+ str(save_dir),+ "Q4_K_M",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is False+ assert "a directory of that name" in message+ assert "upload_folder" not in calls+ assert list((save_dir / "model.Q4_K_M.gguf").iterdir()) == []+ assert (save_dir / "an-earlier-export.Q8_0.gguf").is_file()+++def test_gguf_hub_export_publishes_a_modelfile_blocked_by_a_directory(tmp_path, monkeypatch):+ """A directory named Modelfile would nest it where the allow-list cannot match."""+ save_dir = tmp_path / "export"+ save_dir.mkdir(parents = True)+ (save_dir / "Modelfile").mkdir()++ _install_export_backend_stubs(monkeypatch)+ export_module = _load_module(+ "test_export_gguf_hub_upload_modelfile_dir_backend", "core/export/export.py", monkeypatch+ )++ calls: list[str] = []+ seen: dict = {}++ class Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output = Path(f"{model_save_path}_gguf")+ output.mkdir(parents = True)+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")+ (output / "Modelfile").write_bytes(b"FROM ./model.Q4_K_M.gguf\n")++ def push_to_hub_gguf(self, *args, **kwargs):+ calls.append("push_to_hub_gguf")++ hf_api, model_card = _hub_doubles(calls, seen)+ monkeypatch.setattr(export_module, "HfApi", hf_api)+ monkeypatch.setattr(export_module, "ModelCard", model_card)+ monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))++ backend = export_module.ExportBackend.__new__(export_module.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",+ push_to_hub = True,+ repo_id = "owner/model",+ hf_token = "token",+ private = False,+ )++ assert success is True, message+ assert seen["uploaded"] == ["model.Q4_K_M.gguf"]+ assert seen["Modelfile"] == b"FROM ./model.Q4_K_M.gguf\n"+ assert list((Path(output_path) / "Modelfile").iterdir()) == []diff --git a/studio/backend/tests/test_export_gguf_sharding.py b/studio/backend/tests/test_export_gguf_sharding.pyindex d0db4ce9d93..0565b3d2a01 100644--- a/studio/backend/tests/test_export_gguf_sharding.py+++ b/studio/backend/tests/test_export_gguf_sharding.py@@ -102,7 +102,7 @@ def test_worker_passes_shard_size_to_backend():assert queue.items[-1]["success"] is True-def test_backend_forwards_shard_size_to_local_and_hub_exports(tmp_path, monkeypatch):+def test_backend_forwards_shard_size_to_the_local_export_it_then_uploads(tmp_path, monkeypatch):_install_export_backend_stubs(monkeypatch)export_module = _load_module("test_export_gguf_shard_backend",@@ -127,21 +127,64 @@ def test_backend_forwards_shard_size_to_local_and_hub_exports(tmp_path, monkeypashard.write_bytes(b"GGUF")return {"gguf_files": [str(shard)]}- def push_to_hub_gguf(+ def push_to_hub_gguf(self, *args, **kwargs):+ seen["hub"] = kwargs++ class _RepoUrl(str):+ repo_id = "owner/model"++ class _HfApi:+ def __init__(self, token = None):+ seen["token"] = token++ def create_repo(self,repo_id,- tokenizer,- quantization_method,- token,- private,- gguf_shard_size = None,+ private = False,+ exist_ok = False,+ ):+ seen["repo"] = {"repo_id": repo_id, "private": private}+ return _RepoUrl("https://huggingface.co/owner/model")++ def update_repo_settings(+ self,+ repo_id,+ private = None,+ repo_type = None,+ ):+ seen["visibility"] = {"repo_id": repo_id, "private": private}++ def repo_info(+ self,+ repo_id,+ repo_type = None,+ ):+ return None++ def upload_folder(+ self,+ folder_path,+ repo_id,+ repo_type,+ allow_patterns = None,+ ignore_patterns = None,+ ):+ seen["upload"] = folder_path++ class _ModelCard:+ def __init__(self, content):+ pass++ def push_to_hub(+ self,+ repo_id,+ token = None,+ commit_message = None,):- seen["hub"] = {- "repo_id": repo_id,- "private": private,- "gguf_shard_size": gguf_shard_size,- }+ pass+ monkeypatch.setattr(export_module, "HfApi", _HfApi)+ monkeypatch.setattr(export_module, "ModelCard", _ModelCard)monkeypatch.setattr(export_module, "resolve_export_write_dir", lambda value: Path(value))backend = export_module.ExportBackend.__new__(export_module.ExportBackend)backend.current_model = Model()@@ -161,7 +204,9 @@ def test_backend_forwards_shard_size_to_local_and_hub_exports(tmp_path, monkeypaassert success is True, messageassert output_path == str(save_directory.resolve())assert seen["local"] == "512MB"- assert seen["hub"] == {"repo_id": "owner/model", "private": True, "gguf_shard_size": "512MB"}+ assert "hub" not in seen+ assert seen["upload"] == output_path+ assert seen["repo"] == {"repo_id": "owner/model", "private": True}def test_backend_rejects_old_exporter_only_when_option_is_set(tmp_path, monkeypatch):