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.

Upload all GGUF files in one commit so create_pr opens one pull request (#11857)

Nilay65f27c0f5867
diff --git a/tests/saving/test_push_to_hub_gguf_single_commit.py b/tests/saving/test_push_to_hub_gguf_single_commit.py
new file mode 100644
index 00000000000..e16f3aeb07c
--- /dev/null
+++ b/tests/saving/test_push_to_hub_gguf_single_commit.py
@@ -0,0 +1,123 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+import os
+from types import SimpleNamespace
+
+import huggingface_hub
+import pytest
+
+import unsloth.save as save_mod
+
+
+class _RecordingApi:
+ calls = []
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __getattr__(self, name):
+ def record(*args, **kwargs):
+ if name == "create_commit":
+ readme = next(op for op in kwargs["operations"] if op.path_in_repo == "README.md")
+ kwargs["readme"] = open(readme.path_or_fileobj, encoding = "utf-8").read()
+ _RecordingApi.calls.append((name, kwargs))
+ if name == "create_commit" and kwargs.get("create_pr"):
+ return SimpleNamespace(pr_url = "https://huggingface.co/u/my-model/discussions/1")
+ return SimpleNamespace(pr_url = None)
+
+ return record
+
+
+def _fake_convert(**kwargs):
+ directory = kwargs["save_directory"]
+ os.makedirs(directory, exist_ok = True)
+ stem = os.path.basename(directory)
+ files = []
+ for suffix in ("Q8_0.gguf", "BF16-mmproj.gguf"):
+ path = os.path.join(directory, f"{stem}.{suffix}")
+ open(path, "wb").write(b"GGUF")
+ files.append(path)
+ open(os.path.join(directory, "config.json"), "w").write("{}")
+ modelfile = os.path.join(directory, "Modelfile")
+ open(modelfile, "w").write("FROM x")
+ return {
+ "gguf_files": files,
+ "modelfile_location": modelfile,
+ "want_full_precision": False,
+ "is_vlm": True,
+ "fix_bos_token": False,
+ "save_directory": directory,
+ }
+
+
+def push(monkeypatch):
+ _RecordingApi.calls = []
+ monkeypatch.setattr(huggingface_hub, "HfApi", _RecordingApi)
+ monkeypatch.setattr(save_mod, "unsloth_save_pretrained_gguf", _fake_convert)
+
+ def run(**kwargs):
+ save_mod.unsloth_push_to_hub_gguf(object(), "u/my-model", tokenizer = object(), **kwargs)
+ return _RecordingApi.calls
+
+ return run
+
+
+EXPECTED_PATHS = {
+ "my-model.Q8_0.gguf",
+ "my-model.BF16-mmproj.gguf",
+ "config.json",
+ "Modelfile",
+ "README.md",
+}
+
+
+ "kwargs",
+ [{}, {"create_pr": True}, {"revision": "new-branch"}, {"revision": "refs/pr/3"}],
+)
+def test_all_files_go_in_one_commit(push, kwargs):
+ calls = push(**kwargs)
+ names = [name for name, _ in calls]
+ assert "upload_file" not in names
+ assert names.count("create_commit") == 1
+ commit = next(kw for name, kw in calls if name == "create_commit")
+ assert {op.path_in_repo for op in commit["operations"]} == EXPECTED_PATHS
+ assert commit["create_pr"] == kwargs.get("create_pr", False)
+ assert commit["revision"] == kwargs.get("revision")
+
+
+def test_new_revision_is_created_before_the_commit(push):
+ names = [name for name, _ in push(revision = "new-branch")]
+ assert names.index("create_branch") < names.index("create_commit")
+ branch = next(kw for name, kw in _RecordingApi.calls if name == "create_branch")
+ assert branch["branch"] == "new-branch" and branch["exist_ok"] is True
+
+
[email protected]("kwargs", [{}, {"create_pr": True}, {"revision": "refs/pr/3"}])
+def test_no_branch_is_created_without_a_new_revision(push, kwargs):
+ assert "create_branch" not in [name for name, _ in push(**kwargs)]
+
+
+ "revision, expected",
+ [("exp/q4", "/tree/exp%2Fq4"), ("v2", "/tree/v2"), ("refs/pr/3", "/discussions/3")],
+)
+def test_printed_destination_encodes_the_branch(push, capsys, revision, expected):
+ push(revision = revision)
+ assert f"https://huggingface.co/u/my-model{expected}\n" in capsys.readouterr().out
+
+
[email protected]("datasets", [["org/data", "other"], "org/data"])
+def test_datasets_go_in_the_same_commit(push, monkeypatch, datasets):
+ def fail(*args, **kwargs):
+ raise AssertionError("datasets must not be written in a separate commit")
+
+ monkeypatch.setattr(huggingface_hub, "metadata_update", fail)
+ calls = push(create_pr = True, datasets = datasets)
+ readme = next(kw for name, kw in calls if name == "create_commit")["readme"]
+ card = huggingface_hub.ModelCard(readme)
+ expected = [datasets] if isinstance(datasets, str) else datasets
+ assert card.data.datasets == expected
+ assert "gguf" in card.data.tags
diff --git a/unsloth/save.py b/unsloth/save.py
index 171e4fb60c6..a4ae826c638 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -4590,7 +4590,8 @@ def unsloth_push_to_hub_gguf(
print("Unsloth: Uploading GGUF to Huggingface Hub...")
try:
- from huggingface_hub import HfApi
+ from huggingface_hub import CommitOperationAdd, HfApi
+ from huggingface_hub.errors import HfHubHTTPError
api = HfApi(token = token)
@@ -4606,7 +4607,16 @@ def unsloth_push_to_hub_gguf(
private = private,
exist_ok = True,
)
+ if revision is not None and not revision.startswith("refs/pr/"):
+ try:
+ api.create_branch(
+ repo_id = full_repo_id, repo_type = "model", branch = revision, exist_ok = True
+ )
+ except HfHubHTTPError as error:
+ if not create_pr or error.response.status_code != 403:
+ raise
+ operations = []
for file_location in all_file_locations:
original_name = os.path.basename(file_location)
if cleanup_temp and "unsloth_gguf_" in original_name:
@@ -4616,52 +4626,34 @@ def unsloth_push_to_hub_gguf(
proper_name = f"{model_name}.{quant_suffix}"
else:
proper_name = original_name.replace(os.path.basename(save_directory), model_name)
-
- print(f"Uploading {proper_name}...")
-
- api.upload_file(
- path_or_fileobj = file_location,
- path_in_repo = proper_name,
- repo_id = full_repo_id,
- repo_type = "model",
- commit_message = commit_message,
- commit_description = commit_description,
- create_pr = create_pr,
- revision = revision,
+ operations.append(
+ CommitOperationAdd(path_in_repo = proper_name, path_or_fileobj = file_location)
)
config_path = os.path.join(actual_save_directory, "config.json")
if os.path.exists(config_path):
- print("Uploading config.json...")
- api.upload_file(
- path_or_fileobj = config_path,
- path_in_repo = "config.json",
- repo_id = full_repo_id,
- repo_type = "model",
- commit_message = f"{commit_message} - config",
- create_pr = create_pr,
- revision = revision,
+ operations.append(
+ CommitOperationAdd(path_in_repo = "config.json", path_or_fileobj = config_path)
)
if modelfile_location and os.path.exists(modelfile_location):
- print("Uploading Ollama Modelfile...")
- api.upload_file(
- path_or_fileobj = modelfile_location,
- path_in_repo = "Modelfile",
- repo_id = full_repo_id,
- repo_type = "model",
- commit_message = f"{commit_message} - Ollama Modelfile",
- create_pr = create_pr,
- revision = revision,
+ operations.append(
+ CommitOperationAdd(path_in_repo = "Modelfile", path_or_fileobj = modelfile_location)
)
+ if isinstance(datasets, str):
+ datasets = [datasets]
+ # In the README so it lands in the same commit, not a second one on main.
+ datasets_yaml = "".join(f"- {json.dumps(d)}\n" for d in datasets or [])
+ if datasets_yaml:
+ datasets_yaml = "datasets:\n" + datasets_yaml
readme_content = f"""---
tags:
- gguf
- llama.cpp
- unsloth
{"- vision-language-model" if is_vlm else ""}
----
+{datasets_yaml}---
# {repo_id.split("/")[-1]} : GGUF
@@ -4673,16 +4665,8 @@ This model was finetuned and converted to GGUF format using [Unsloth](https://gi
## Available Model files:
"""
- for file in all_file_locations:
- original_name = os.path.basename(file)
- if cleanup_temp and "unsloth_gguf_" in original_name:
- quant_suffix = (
- original_name.split(".", 1)[1] if "." in original_name else original_name
- )
- proper_name = f"{model_name}.{quant_suffix}"
- else:
- proper_name = original_name.replace(os.path.basename(save_directory), model_name)
- readme_content += f"- `{proper_name}`\n"
+ for operation in operations[: len(all_file_locations)]:
+ readme_content += f"- `{operation.path_in_repo}`\n"
if is_vlm and modelfile_location:
readme_content += "\n## ⚠️ Ollama Note for Vision Models\n"
@@ -4711,17 +4695,33 @@ This model was finetuned and converted to GGUF format using [Unsloth](https://gi
with open(readme_path, "w", encoding = "utf-8") as f:
f.write(readme_content)
- api.upload_file(
- path_or_fileobj = readme_path,
- path_in_repo = "README.md",
+ operations.append(CommitOperationAdd(path_in_repo = "README.md", path_or_fileobj = readme_path))
+
+ commit = api.create_commit(
repo_id = full_repo_id,
repo_type = "model",
- commit_message = "Add README",
+ operations = operations,
+ commit_message = (
+ commit_message if commit_message is not None else "Trained with Unsloth"
+ ),
+ commit_description = commit_description,
create_pr = create_pr,
revision = revision,
)
- print(f"Unsloth: Successfully uploaded GGUF to https://huggingface.co/{full_repo_id}")
+ destination = getattr(commit, "pr_url", None)
+ if destination is None:
+ from urllib.parse import quote
+ destination = f"https://huggingface.co/{full_repo_id}"
+ if create_pr:
+ destination += "/discussions"
+ elif revision is not None:
+ destination += (
+ f"/discussions/{revision.rsplit('/', 1)[-1]}"
+ if revision.startswith("refs/pr/")
+ else f"/tree/{quote(revision, safe = '')}"
+ )
+ print(f"Unsloth: Successfully uploaded GGUF to {destination}")
if tags is None:
tags = []
@@ -4738,15 +4738,6 @@ This model was finetuned and converted to GGUF format using [Unsloth](https://gi
except:
pass
- if datasets:
- try:
- from huggingface_hub import metadata_update
- metadata_update(full_repo_id, {"datasets": datasets}, overwrite = True, token = token)
- except Exception as e:
- logger.warning_once(
- f"Unsloth: Could not update datasets metadata for {full_repo_id}: {e}"
- )
-
except Exception as e:
raise RuntimeError(f"Failed to upload to Hugging Face Hub: {_describe_exception(e)}") from e