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.

Studio: detect real GGUF imatrix support, and give the local export its credential (#8603)

Long Yixing0c6c1b9a972e
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py
index a005fb11f7c..806f92732a5 100644
--- a/studio/backend/core/export/export.py
+++ b/studio/backend/core/export/export.py
@@ -155,6 +155,18 @@ def _cpu_offloaded_modules(model) -> int:
return sum(1 for target in device_map.values() if str(target) in ("cpu", "disk"))
+def _accepts_by_keyword(params, name):
+ """True if `name` is passable as a keyword, not merely named.
+
+ Every call site passes by keyword, so a positional-only parameter is not support: counting
+ it turns a clean refusal into a TypeError.
+ """
+ import inspect
+
+ parameter = params.get(name)
+ return parameter is not None and parameter.kind is not inspect.Parameter.POSITIONAL_ONLY
+
+
def _supports_kwarg(fn, name):
"""True if `fn` accepts keyword `name` directly or via **kwargs."""
import inspect
@@ -163,7 +175,30 @@ def _supports_kwarg(fn, name):
params = inspect.signature(fn).parameters
except (TypeError, ValueError):
return False
- return name in params or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
+ return _accepts_by_keyword(params, name) or any(
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()
+ )
+
+
+def _imatrix_export_supported(save_fn):
+ """True when this build can apply an imatrix, not merely swallow the keyword: the MLX binding
+ takes `**kwargs` and filters them, so only unsloth_zoo itself settles it."""
+ import inspect
+
+ try:
+ params = inspect.signature(save_fn).parameters
+ except (TypeError, ValueError):
+ return False
+ if _accepts_by_keyword(params, "imatrix_file"):
+ return True
+ if not any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()):
+ return False
+ try:
+ from unsloth_zoo.llama_cpp import resolve_imatrix_file # noqa: F401
+ except Exception:
+ # Runs before export_gguf's exception boundary, which must return a tuple, not raise.
+ return False
+ return True
def _reported_gguf_files(result):
@@ -195,9 +230,8 @@ def _materialized_imatrix_path(model_dir, imatrix_file):
"""Where unsloth copies a `*.gguf_file` imatrix beside the model, else None.
`_materialize_imatrix` drops that copy in the model directory, so the owned-root scan
- would otherwise relocate an importance matrix as if it were a converted model. Matching
- the full path, not the basename: an imatrix named after the quant would otherwise
- suppress the real output in `model_gguf/` as well.
+ would otherwise relocate it as if it were a converted model. Callers compare the whole path
+ (see `_is_imatrix`): a basename match would suppress a real output of the same name.
"""
if imatrix_file is True:
name = "imatrix_unsloth.gguf" # the upstream imatrix_unsloth.gguf_file, renamed
@@ -211,6 +245,26 @@ def _materialized_imatrix_path(model_dir, imatrix_file):
return Path(model_dir) / name
+def _is_imatrix(path, imatrix_path):
+ """True when `path` is the materialized imatrix, asked of the filesystem rather than `==`.
+
+ The on-disk spelling is the filesystem's to choose (a folding mount changes case, APFS
+ stores NFD), so byte-exact `Path.__eq__` misses and the imatrix is relocated as a model.
+ """
+ if imatrix_path is None:
+ return False
+ try:
+ return os.path.samefile(path, imatrix_path)
+ except OSError:
+ # Either side may be gone by cleanup time; fall back to a folded comparison.
+ return _folded(path) == _folded(imatrix_path)
+
+
+def _folded(path):
+ import unicodedata
+ return unicodedata.normalize("NFC", os.path.normcase(os.fspath(path)))
+
+
def _compressed_export_supported():
"""True if the installed unsloth build can do FP8/NVFP4 compressed-tensors export."""
try:
@@ -1030,16 +1084,24 @@ class ExportBackend:
# Only forward imatrix_file to an unsloth build that accepts it, else older builds raise
# an unexpected-keyword error even for a plain no-imatrix export.
- if imatrix_file is not None and not _supports_kwarg(
- self.current_model.save_pretrained_gguf, "imatrix_file"
- ):
+ if imatrix_file and not _imatrix_export_supported(self.current_model.save_pretrained_gguf):
return (
False,
"This Unsloth build does not support GGUF imatrix export. "
"Upgrade unsloth and unsloth_zoo, or disable the imatrix option.",
None,
)
- imatrix_kw = {"imatrix_file": imatrix_file} if imatrix_file is not None else {}
+ # Truthiness, as above: a disabled imatrix must not reach an exporter without the kwarg.
+ imatrix_kw = {"imatrix_file": imatrix_file} if imatrix_file else {}
+ # Resolution reads a Hub repo, so the local save needs the token too -- kept out of
+ # imatrix_kw, which the push below shares and already names token= itself.
+ local_token_kw = (
+ {"token": hf_token}
+ if imatrix_file
+ and hf_token
+ and _supports_kwarg(self.current_model.save_pretrained_gguf, "token")
+ else {}
+ )
output_path: Optional[str] = None
try:
@@ -1061,7 +1123,9 @@ class ExportBackend:
_resolve_local_convert_script, # noqa: F401
)
os.environ.setdefault("UNSLOTH_LLAMA_CPP_SCRIPTS_DIR", LLAMA_CPP_DEFAULT_DIR)
- except ImportError:
+ except Exception:
+ # Not just ImportError: a half-built unsloth_zoo raises RuntimeError or
+ # AttributeError, and this pin is an optimisation, not worth failing an export.
if not _LLAMA_CPP_SCRIPTS_WARNING_EMITTED:
logger.warning(
"Unsloth: installed unsloth_zoo does not honor "
@@ -1095,13 +1159,14 @@ class ExportBackend:
self.current_tokenizer,
quantization_method = quant_method,
**imatrix_kw,
+ **local_token_kw,
)
# Scan only the owned root; exact reported paths cover external outputs.
reported = result if isinstance(result, dict) else {}
produced = {p for p in model_tmp_path.rglob("*.gguf") if p.is_file()}
produced.update(Path(f) for f in _reported_gguf_files(result) or [])
- produced = {p for p in produced if p != imatrix_path}
+ produced = {p for p in produced if not _is_imatrix(p, imatrix_path)}
modelfiles = {p for p in model_tmp_path.rglob("Modelfile") if p.is_file()}
reported_modelfile = reported.get("modelfile_location")
if reported_modelfile and Path(reported_modelfile).is_file():
@@ -1143,7 +1208,9 @@ class ExportBackend:
unrelocated = []
if model_tmp_path.is_dir():
unrelocated = sorted(
- str(p) for p in model_tmp_path.rglob("*.gguf") if p != imatrix_path
+ str(p)
+ for p in model_tmp_path.rglob("*.gguf")
+ if not _is_imatrix(p, imatrix_path)
)
if unrelocated:
logger.error(
diff --git a/studio/backend/tests/test_export_gguf_discovery.py b/studio/backend/tests/test_export_gguf_discovery.py
index a8be7d8343a..c31a84a9c88 100644
--- a/studio/backend/tests/test_export_gguf_discovery.py
+++ b/studio/backend/tests/test_export_gguf_discovery.py
@@ -15,6 +15,8 @@ from __future__ import annotations
import os
import sys
+import types
+import unicodedata
from pathlib import Path
import pytest
@@ -424,3 +426,309 @@ def test_modelfile_relocation_failure_does_not_fail_the_export(monkeypatch, tmp_
assert success is True, message
assert (save_dir / "MyModel.Q5_K_M.gguf").is_file()
assert not (save_dir / "Modelfile").exists()
+
+
+# The upstream imatrix lives in a Hub repo, so the local export needs the token too -- without
+# disturbing the push path, which already passes it explicitly.
+
+
+def _imatrix_model(accepts_token: bool, calls: dict):
+ class _WithToken:
+ def save_pretrained_gguf(
+ self,
+ model_save_path,
+ tokenizer,
+ quantization_method,
+ imatrix_file = None,
+ token = None,
+ ):
+ calls["save"] = {"imatrix_file": imatrix_file, "token": token}
+ _gguf(Path(model_save_path) / "Model.IQ2_XXS.gguf")
+
+ def push_to_hub_gguf(
+ self,
+ repo_id,
+ tokenizer,
+ quantization_method = None,
+ token = None,
+ imatrix_file = None,
+ ):
+ calls["push"] = {"repo_id": repo_id, "token": token, "imatrix_file": imatrix_file}
+
+ class _WithoutToken:
+ def save_pretrained_gguf(
+ self,
+ model_save_path,
+ tokenizer,
+ quantization_method,
+ imatrix_file = None,
+ ):
+ calls["save"] = {"imatrix_file": imatrix_file}
+ _gguf(Path(model_save_path) / "Model.IQ2_XXS.gguf")
+
+ return (_WithToken if accepts_token else _WithoutToken)()
+
+
+def test_local_gguf_export_forwards_the_token_for_the_upstream_imatrix(monkeypatch, tmp_path):
+ calls: dict = {}
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(True, calls))
+
+ success, message, _p = backend.export_gguf(
+ str(save_dir), "iq2_xxs", hf_token = "hf_secret", imatrix_file = True
+ )
+
+ assert success is True, message
+ assert 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."""
+ calls: dict = {}
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(True, calls))
+
+ success, message, _p = backend.export_gguf(
+ str(save_dir),
+ "iq2_xxs",
+ push_to_hub = True,
+ repo_id = "org/model",
+ hf_token = "hf_secret",
+ imatrix_file = True,
+ )
+
+ assert success is True, message
+ assert calls["push"] == {"repo_id": "org/model", "token": "hf_secret", "imatrix_file": True}
+
+
+def test_gguf_export_without_an_imatrix_does_not_forward_the_token(monkeypatch, tmp_path):
+ calls: dict = {}
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(True, calls))
+
+ success, message, _p = backend.export_gguf(str(save_dir), "q4_k_m", hf_token = "hf_secret")
+
+ assert success is True, message
+ assert calls["save"] == {"imatrix_file": None, "token": None}
+
+
+def test_older_build_without_token_support_still_exports(monkeypatch, tmp_path):
+ calls: dict = {}
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(False, calls))
+
+ success, message, _p = backend.export_gguf(
+ str(save_dir), "iq2_xxs", hf_token = "hf_secret", imatrix_file = True
+ )
+
+ assert success is True, message
+ assert calls["save"] == {"imatrix_file": True}
+
+
+class _KwargsOnlyModel:
+ """The MLX binding's shape: it accepts anything and filters against an allow-list."""
+
+ def __init__(self, calls):
+ self._calls = calls
+
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method, **kwargs):
+ self._calls["save"] = kwargs
+ _gguf(Path(model_save_path) / "Model.IQ2_XXS.gguf")
+
+
+def test_imatrix_refused_when_unsloth_zoo_cannot_apply_it(monkeypatch, tmp_path):
+ """A kwargs-only binding proves nothing: an older zoo would swallow the imatrix silently."""
+ calls: dict = {}
+ module, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _KwargsOnlyModel(calls))
+ monkeypatch.setattr(module, "_imatrix_export_supported", lambda save_fn: False, raising = True)
+
+ success, message, _p = backend.export_gguf(str(save_dir), "iq2_xxs", imatrix_file = True)
+
+ assert success is False
+ assert "imatrix" in message.lower()
+ assert calls == {}, "must not spend a merge and conversion first"
+
+
+def test_imatrix_export_supported_probes_unsloth_zoo_for_kwargs_only_bindings(
+ monkeypatch, tmp_path
+):
+ module, _b, _s, _cwd = _backend(monkeypatch, tmp_path, object())
+ zoo = sys.modules.get("unsloth_zoo.llama_cpp")
+
+ def named(
+ save_directory,
+ tokenizer,
+ quantization_method,
+ imatrix_file = None,
+ ):
+ pass
+
+ def kwargs_only(save_directory, tokenizer, quantization_method, **kwargs):
+ pass
+
+ def positional_only(save_directory, tokenizer, quantization_method):
+ pass
+
+ # A build that names the argument needs no zoo probe at all.
+ assert module._imatrix_export_supported(named) is True
+ assert module._imatrix_export_supported(positional_only) is False
+
+ fake_zoo = types.ModuleType("unsloth_zoo.llama_cpp")
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.llama_cpp", fake_zoo)
+ assert module._imatrix_export_supported(kwargs_only) is False, "no resolver -> old zoo"
+ fake_zoo.resolve_imatrix_file = lambda *a, **kw: None
+ assert module._imatrix_export_supported(kwargs_only) is True
+ if zoo is not None:
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.llama_cpp", zoo)
+
+
+def test_imatrix_disabled_explicitly_does_not_forward_the_token(monkeypatch, tmp_path):
+ calls: dict = {}
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(True, calls))
+
+ success, message, _p = backend.export_gguf(
+ str(save_dir), "q4_k_m", hf_token = "hf_secret", imatrix_file = False
+ )
+
+ assert success is True, message
+ # Neither the credential nor the disabled flag itself is forwarded.
+ assert calls["save"] == {"imatrix_file": None, "token": None}
+
+
+def test_disabled_imatrix_is_never_blocked_by_the_capability_probe(monkeypatch, tmp_path):
+ """imatrix_file=False asks for no imatrix, so an old zoo must not refuse the export."""
+ calls: dict = {}
+ module, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _KwargsOnlyModel(calls))
+ monkeypatch.setattr(
+ module,
+ "_imatrix_export_supported",
+ lambda save_fn: pytest.fail("no imatrix was requested"),
+ raising = True,
+ )
+
+ success, message, _p = backend.export_gguf(str(save_dir), "q4_k_m", imatrix_file = False)
+
+ assert success is True, message
+
+
+def test_broken_unsloth_zoo_yields_a_failure_tuple_not_an_exception(monkeypatch, tmp_path):
+ """The probe runs before export_gguf's try block, so it must swallow more than ImportError."""
+ module, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _KwargsOnlyModel({}))
+
+ class _Exploding(types.ModuleType):
+ def __getattr__(self, name):
+ raise RuntimeError("partially initialised unsloth_zoo")
+
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.llama_cpp", _Exploding("unsloth_zoo.llama_cpp"))
+
+ success, message, _p = backend.export_gguf(str(save_dir), "iq2_xxs", imatrix_file = True)
+
+ assert success is False
+ assert "imatrix" in message.lower()
+
+
+class _OldSaver:
+ """Predates the imatrix kwarg entirely: no `imatrix_file`, no `**kwargs`."""
+
+ def __init__(self, calls):
+ self._calls = calls
+
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ self._calls["save"] = quantization_method
+ _gguf(Path(model_save_path) / "Model.Q4_K_M.gguf")
+
+
+def test_disabled_imatrix_does_not_reach_an_older_exporter(monkeypatch, tmp_path):
+ """imatrix_file=False means off, so the keyword must be omitted, not passed as False."""
+ calls: dict = {}
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _OldSaver(calls))
+
+ success, message, _p = backend.export_gguf(str(save_dir), "q4_k_m", imatrix_file = False)
+
+ assert success is True, message
+ assert calls["save"] == "q4_k_m"
+
+
+# A probe that says "supported" must be right about the call it authorises, and the
+# materialized imatrix must stay an input under whichever name the filesystem gave it.
+
+
+def test_a_positional_only_imatrix_parameter_is_not_support(monkeypatch, tmp_path):
+ """Named is not passable by keyword, and every call site passes one."""
+ module, _b, _s, _cwd = _backend(monkeypatch, tmp_path, object())
+
+ namespace: dict = {}
+ exec(
+ "def f(save_directory, tokenizer, quantization_method, imatrix_file = None,"
+ " token = None, /): pass",
+ namespace,
+ )
+
+ with pytest.raises(TypeError):
+ namespace["f"]("d", "t", "q", imatrix_file = True)
+ assert module._imatrix_export_supported(namespace["f"]) is False
+ assert module._supports_kwarg(namespace["f"], "token") is False
+
+
+class _ImatrixNamingModel:
+ """Writes the imatrix under the name the filesystem chose, as a folding or NFD mount does."""
+
+ def __init__(self, on_disk_name):
+ self.on_disk_name = on_disk_name
+
+ def save_pretrained_gguf(
+ self,
+ model_save_path,
+ tokenizer,
+ quantization_method,
+ imatrix_file = None,
+ token = None,
+ ):
+ _gguf(Path(model_save_path) / "Model.IQ2_XXS.gguf")
+ _gguf(Path(model_save_path) / self.on_disk_name)
+
+
+_NFC = unicodedata.normalize("NFC", "im\u00e4trix")
+_NFD = unicodedata.normalize("NFD", "im\u00e4trix")
+
+
+ "on_disk,requested",
+ [
+ ("imatrix_unsloth.gguf", "/x/imatrix_unsloth.gguf_file"),
+ (f"{_NFD}.gguf", f"/x/{_NFC}.gguf_file"), # APFS stores NFD, the request carried NFC
+ (f"{_NFC}.gguf", f"/x/{_NFD}.gguf_file"), # and the other way round
+ ],
+)
+def test_the_materialized_imatrix_is_never_exported_as_a_model(
+ monkeypatch, tmp_path, on_disk, requested
+):
+ _m, backend, save_dir, _cwd = _backend(
+ monkeypatch,
+ tmp_path,
+ _ImatrixNamingModel(on_disk),
+ )
+
+ success, message, _p = backend.export_gguf(
+ str(save_dir),
+ "iq2_xxs",
+ imatrix_file = requested,
+ )
+
+ assert success is True, message
+ landed = sorted(p.name for p in save_dir.iterdir() if p.suffix == ".gguf")
+ assert landed == ["Model.IQ2_XXS.gguf"], f"the imatrix was exported as a model: {landed}"
+
+
+def test_a_broken_unsloth_zoo_does_not_fail_a_plain_export(monkeypatch, tmp_path):
+ """The scripts pin is an optimisation, so a half-built zoo must not fail the export: it
+ raises RuntimeError or AttributeError, which `except ImportError` did not catch."""
+
+ class _Exploding(types.ModuleType):
+ def __getattr__(self, name):
+ raise RuntimeError("half-built native dep")
+
+ calls: dict = {}
+ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _imatrix_model(True, calls))
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.llama_cpp", _Exploding("unsloth_zoo.llama_cpp"))
+
+ success, message, _p = backend.export_gguf(str(save_dir), "q4_k_m")
+
+ assert success is True, message
+ assert calls["save"] == {"imatrix_file": None, "token": None}
diff --git a/studio/backend/tests/test_export_imatrix_compressed.py b/studio/backend/tests/test_export_imatrix_compressed.py
index f499390addc..2af03b3cd87 100644
--- a/studio/backend/tests/test_export_imatrix_compressed.py
+++ b/studio/backend/tests/test_export_imatrix_compressed.py
@@ -57,15 +57,17 @@ def test_export_gguf_threads_imatrix_to_save_and_push():
# imatrix_file must reach both save paths, but only via the conditional **imatrix_kw.
g = _func_src("core/export/export.py", "export_gguf")
assert g.count("**imatrix_kw") >= 2
- assert 'imatrix_kw = {"imatrix_file": imatrix_file} if imatrix_file is not None else {}' in g
+ # Truthiness, not `is not None`: a disabled imatrix must not reach an exporter without the kwarg.
+ assert 'imatrix_kw = {"imatrix_file": imatrix_file} if imatrix_file else {}' in g
# Unconditional pass-through (the old wiring) must be gone.
assert "imatrix_file = imatrix_file" not in g
def test_export_gguf_guards_unsupported_imatrix_build():
- # An older unsloth without imatrix_file support gets a clean error, not a TypeError.
+ # A build that cannot apply an imatrix gets a clean error, not a TypeError or a silent drop.
+ # The kwarg probe is not enough here: the MLX binding takes **kwargs and filters them.
g = _func_src("core/export/export.py", "export_gguf")
- assert "_supports_kwarg(" in g and '"imatrix_file"' in g
+ assert "_imatrix_export_supported(" in g
def test_export_merged_guards_unsupported_compressed_build():
@@ -76,7 +78,8 @@ def test_export_merged_guards_unsupported_compressed_build():
def test_supports_kwarg_helper():
# exec just the helper source so the test stays free of export.py's heavy import chain.
ns = {}
- exec(_func_src("core/export/export.py", "_supports_kwarg"), ns)
+ for helper in ("_accepts_by_keyword", "_supports_kwarg"):
+ exec(_func_src("core/export/export.py", helper), ns)
supports = ns["_supports_kwarg"]
def has_it(a, imatrix_file = None):
@@ -88,9 +91,14 @@ def test_supports_kwarg_helper():
def via_kwargs(a, **kw):
pass
+ # Named but unusable: every call site passes the keyword, so this is not support.
+ positional_only = {}
+ exec("def f(a, imatrix_file = None, /): pass", positional_only)
+
assert supports(has_it, "imatrix_file") is True
assert supports(lacks_it, "imatrix_file") is False
assert supports(via_kwargs, "imatrix_file") is True
+ assert supports(positional_only["f"], "imatrix_file") is False
def test_orchestrator_and_worker_pass_imatrix():
@@ -163,6 +171,36 @@ def test_unsloth_save_has_torchao_registry_and_path():
assert '"torchao_int8": ("int8", "torchao-int8")' in save_py
[email protected]("wrapper_name", ["_save_pretrained_gguf", "_push_to_hub_gguf"])
+def test_sentence_transformer_gguf_wrappers_forward_imatrix(wrapper_name):
+ # Both take **kwargs, so the probe reads them as supported once unsloth_zoo can resolve an
+ # imatrix; they must therefore forward the argument rather than swallow it.
+ st = (_BACKEND.parent.parent / "unsloth" / "models" / "sentence_transformer.py").read_text(
+ encoding = "utf-8"
+ )
+ wrapper = st[st.index(f"def {wrapper_name}(") :]
+ wrapper = wrapper[: wrapper.index("\n# ")]
+ assert "imatrix_file = None," in wrapper
+ assert "imatrix_file = imatrix_file," in wrapper
+
+
+def test_gguf_export_request_falls_back_to_the_load_token():
+ # A local imatrix export resolves from a Hub repo, but the UI only sets `token` for a hub push,
+ # so the GGUF payload has to fall back the way the LoRA payload already does.
+ store = (
+ _BACKEND.parent
+ / "frontend"
+ / "src"
+ / "features"
+ / "export"
+ / "stores"
+ / "export-runtime-store.ts"
+ ).read_text(encoding = "utf-8")
+ gguf = store[store.index("exportGGUF({") :]
+ gguf = gguf[: gguf.index("}),")]
+ assert "hf_token: params.token ?? params.loadToken ?? null," in gguf
+
+
# -- GGUF multi-quant list ----------------------------------------------------------------------
diff --git a/studio/frontend/src/features/export/stores/export-runtime-store.ts b/studio/frontend/src/features/export/stores/export-runtime-store.ts
index 6ee5c789948..58abde35ba8 100644
--- a/studio/frontend/src/features/export/stores/export-runtime-store.ts
+++ b/studio/frontend/src/features/export/stores/export-runtime-store.ts
@@ -491,7 +491,9 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
quantization_method: params.quantLevels,
push_to_hub: pushToHub,
repo_id: params.repoId,
- hf_token: params.token,
+ // A local imatrix export resolves the matrix from a Hub repo, so fall back to the load
+ // token when there is no hub-upload token (both are the same HF token).
+ hf_token: params.token ?? params.loadToken ?? null,
imatrix: params.useImatrix,
}),
);
diff --git a/studio/frontend/tests/export-gguf-token-fallback.test.ts b/studio/frontend/tests/export-gguf-token-fallback.test.ts
new file mode 100644
index 00000000000..a1b73bd0faa
--- /dev/null
+++ b/studio/frontend/tests/export-gguf-token-fallback.test.ts
@@ -0,0 +1,104 @@
+// 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 stub = await import("./helpers/export-api-stub.mjs");
+const { useExportRuntimeStore } = await import(
+ "../src/features/export/stores/export-runtime-store.ts"
+);
+
+// A local imatrix export resolves the matrix from a Hub repo, but export-page.tsx only sets
+// `token` for a hub push, so the GGUF request falls back to the load token as the LoRA request
+// already does. Asserting the emitted body, not the source, so a refactor still passes.
+
+function params(overrides: Record<string, unknown>) {
+ return {
+ sourceMode: "model",
+ checkpointPath: null,
+ source: "unsloth/Qwen3-0.6B",
+ modelSource: "hf",
+ trustRemoteCode: false,
+ exportMethod: "gguf",
+ isAdapter: false,
+ quantLevels: ["iq2_xxs"],
+ saveDirectory: "out",
+ destination: "local",
+ privateRepo: false,
+ summary: {},
+ ...overrides,
+ } as unknown as Parameters<
+ ReturnType<typeof useExportRuntimeStore.getState>["runExport"]
+ >[0];
+}
+
+async function ggufRequest(overrides: Record<string, unknown>) {
+ stub.resetStub();
+ await useExportRuntimeStore.getState().runExport(params(overrides));
+ const call = stub.calls.find((entry) => entry.name === "exportGGUF");
+ assert.ok(call, "no GGUF export request was made");
+ return call.args[0] as Record<string, unknown>;
+}
+
+test("a local imatrix export falls back to the load token", async () => {
+ const body = await ggufRequest({
+ useImatrix: true,
+ loadToken: "hf_load",
+ token: undefined,
+ destination: "local",
+ });
+
+ assert.equal(body.hf_token, "hf_load");
+ assert.equal(body.imatrix, true);
+ assert.equal(body.push_to_hub, false);
+});
+
+test("a hub push prefers its own upload token over the load token", async () => {
+ const body = await ggufRequest({
+ useImatrix: true,
+ loadToken: "hf_load",
+ token: "hf_upload",
+ destination: "hub",
+ repoId: "org/model",
+ });
+
+ assert.equal(body.hf_token, "hf_upload");
+ assert.equal(body.repo_id, "org/model");
+ assert.equal(body.push_to_hub, true);
+});
+
+test("no token anywhere sends null rather than undefined", async () => {
+ const body = await ggufRequest({ useImatrix: true, loadToken: null, token: undefined });
+
+ // undefined would be dropped by JSON.stringify and the field would go missing entirely.
+ assert.equal(body.hf_token, null);
+ assert.ok("hf_token" in body);
+});
+
+test("the fallback matches the LoRA request, which already had it", async () => {
+ const gguf = await ggufRequest({ useImatrix: true, loadToken: "hf_load", token: undefined });
+
+ stub.resetStub();
+ await useExportRuntimeStore.getState().runExport(
+ params({ exportMethod: "lora", loadToken: "hf_load", token: undefined }),
+ );
+ const lora = stub.calls.find((entry) => entry.name === "exportLoRA");
+ assert.ok(lora, "no LoRA export request was made");
+
+ assert.equal(gguf.hf_token, (lora.args[0] as Record<string, unknown>).hf_token);
+});
+
+test("the load phase keeps using the load token on its own", async () => {
+ stub.resetStub();
+ await useExportRuntimeStore.getState().runExport(
+ params({ useImatrix: true, loadToken: "hf_load", token: "hf_upload", destination: "hub",
+ repoId: "org/model" }),
+ );
+ const load = stub.calls.find((entry) => entry.name === "loadCheckpoint");
+ assert.ok(load, "no load request was made");
+ assert.equal((load.args[0] as Record<string, unknown>).hf_token, "hf_load");
+});
diff --git a/studio/frontend/tests/helpers/export-api-stub.d.mts b/studio/frontend/tests/helpers/export-api-stub.d.mts
new file mode 100644
index 00000000000..544c47129b1
--- /dev/null
+++ b/studio/frontend/tests/helpers/export-api-stub.d.mts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Types for export-api-stub.mjs so a .ts test can read the recorded calls without `any`.
+
+export declare const calls: { name: string; args: unknown[] }[];
+export declare const responses: Map<string, unknown>;
+
+export declare function resetStub(): void;
+
+export declare const loadCheckpoint: (...args: unknown[]) => Promise<unknown>;
+export declare const exportGGUF: (...args: unknown[]) => Promise<unknown>;
+export declare const exportMerged: (...args: unknown[]) => Promise<unknown>;
+export declare const exportLoRA: (...args: unknown[]) => Promise<unknown>;
+export declare const cleanupExport: (...args: unknown[]) => Promise<unknown>;
+export declare const cancelExport: (...args: unknown[]) => Promise<unknown>;
+export declare const getExportStatus: (...args: unknown[]) => Promise<unknown>;
+
+export declare function isRecoverableTransportError(): boolean;
diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.py
index c0c7fc58897..29a27260ff3 100644
--- a/unsloth/models/sentence_transformer.py
+++ b/unsloth/models/sentence_transformer.py
@@ -163,6 +163,7 @@ def _save_pretrained_gguf(
max_shard_size = "5GB",
temporary_location = "_unsloth_temporary_saved_buffers",
maximum_memory_usage = 0.85,
+ imatrix_file = None,
**kwargs,
):
"""
@@ -212,6 +213,7 @@ def _save_pretrained_gguf(
max_shard_size = max_shard_size,
temporary_location = temporary_location,
maximum_memory_usage = maximum_memory_usage,
+ imatrix_file = imatrix_file,
)
# 5. Move GGUF files from the subdirectory (0_Transformer) to the root save_directory
@@ -298,6 +300,7 @@ def _push_to_hub_gguf(
create_pr = False,
revision = None,
tags = None,
+ imatrix_file = None,
**kwargs,
):
"""
@@ -389,6 +392,7 @@ def _push_to_hub_gguf(
max_shard_size = max_shard_size,
temporary_location = temporary_location,
maximum_memory_usage = maximum_memory_usage,
+ imatrix_file = imatrix_file,
)
gguf_files = result.get("gguf_files", [])