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: imatrix GGUF option and FP8/NVFP4 compressed export in the export UI (#6729)

Daniel Han43d3caf38b9b
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py
index f243f5b65a1..d0461dae952 100644
--- a/studio/backend/core/export/export.py
+++ b/studio/backend/core/export/export.py
@@ -38,6 +38,26 @@ logger = get_logger(__name__)
_LLAMA_CPP_SCRIPTS_WARNING_EMITTED = False
+def _supports_kwarg(fn, name):
+ """True if `fn` accepts keyword `name` directly or via **kwargs."""
+ import inspect
+
+ try:
+ 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())
+
+
+def _compressed_export_supported():
+ """True if the installed unsloth build can do FP8/NVFP4 compressed-tensors export."""
+ try:
+ import unsloth.save as _us
+ return hasattr(_us, "_normalize_compressed_method")
+ except Exception:
+ return False
+
+
def _hf_offline(timeout = 3):
"""True if export should avoid the Hub: honors the HF offline env vars, else does one
cheap TCP reachability probe so a network-down load uses local files / the HF cache
@@ -400,16 +420,33 @@ class ExportBackend:
)
output_path: Optional[str] = None
+ # compressed-tensors formats run save_pretrained_merged with an FP8/FP4 save_method and
+ # write to a sibling "<dir>-<suffix>" directory (for vLLM).
+ _COMPRESSED = {
+ "FP8 (compressed-tensors)": ("fp8", "fp8"),
+ "NVFP4 (compressed-tensors)": ("nvfp4", "nvfp4"),
+ }
+ is_compressed = format_type in _COMPRESSED
try:
if _IS_MLX:
+ if is_compressed:
+ return False, "Compressed-tensors export is not supported on macOS/MLX.", None
mlx_save_method = "merged_4bit" if format_type == "4-bit (FP4)" else "merged_16bit"
+ elif is_compressed:
+ if not _compressed_export_supported():
+ return (
+ False,
+ "Compressed-tensors (FP8/NVFP4) export requires an Unsloth build with "
+ "compressed-tensors support. Upgrade unsloth, or choose 16-bit.",
+ None,
+ )
+ save_method = _COMPRESSED[format_type][0]
+ elif format_type == "4-bit (FP4)":
+ save_method = "merged_4bit_forced"
+ elif self._audio_type == "whisper":
+ save_method = None
else:
- if format_type == "4-bit (FP4)":
- save_method = "merged_4bit_forced"
- elif self._audio_type == "whisper":
- save_method = None
- else:
- save_method = "merged_16bit"
+ save_method = "merged_16bit"
if save_directory:
save_directory = str(resolve_export_write_dir(save_directory))
@@ -427,9 +464,15 @@ class ExportBackend:
save_directory, self.current_tokenizer, save_method = save_method
)
- self._write_export_metadata(save_directory)
- logger.info(f"Model saved successfully to {save_directory}")
- output_path = str(Path(save_directory).resolve())
+ # Compressed export writes to the "<dir>-<suffix>" sibling; report that as output.
+ final_dir = (
+ f"{save_directory}-{_COMPRESSED[format_type][1]}"
+ if is_compressed
+ else save_directory
+ )
+ self._write_export_metadata(final_dir)
+ logger.info(f"Model saved successfully to {final_dir}")
+ output_path = str(Path(final_dir).resolve())
if push_to_hub:
if not repo_id or not hf_token:
@@ -464,6 +507,32 @@ class ExportBackend:
token = hf_token,
private = private,
)
+ elif is_compressed and output_path and Path(output_path).is_dir():
+ # The compressed model was already built locally in output_path; upload it
+ # directly so we do not re-run the (expensive, OOM-prone) compression that
+ # push_to_hub_merged(save_method=fp8/nvfp4) would otherwise do a second time.
+ hf_api = HfApi(token = hf_token)
+ repo_id = PushToHubMixin._create_repo(
+ PushToHubMixin,
+ repo_id = repo_id,
+ private = private,
+ token = hf_token,
+ )
+ content = MODEL_CARD.format(
+ username = repo_id.split("/")[0],
+ base_model = getattr(self.current_model.config, "_name_or_path", "unknown"),
+ model_type = getattr(self.current_model.config, "model_type", "llm"),
+ method = format_type,
+ extra = "unsloth",
+ )
+ ModelCard(content).push_to_hub(
+ repo_id, token = hf_token, commit_message = "Unsloth Model Card"
+ )
+ hf_api.upload_folder(
+ folder_path = output_path,
+ repo_id = repo_id,
+ repo_type = "model",
+ )
else:
hub_save_method = save_method if save_method is not None else "merged_16bit"
self.current_model.push_to_hub_merged(
@@ -621,6 +690,7 @@ class ExportBackend:
push_to_hub: bool = False,
repo_id: Optional[str] = None,
hf_token: Optional[str] = None,
+ imatrix_file = None,
) -> Tuple[bool, str, Optional[str]]:
"""
Export model in GGUF format.
@@ -638,6 +708,19 @@ class ExportBackend:
if not self.current_model or not self.current_tokenizer:
return False, "No model loaded. Please select a checkpoint first.", None
+ # Only forward imatrix_file to an unsloth build that accepts it; otherwise even a plain
+ # no-imatrix export would fail with an unexpected-keyword error against an older unsloth.
+ if imatrix_file is not None and not _supports_kwarg(
+ self.current_model.save_pretrained_gguf, "imatrix_file"
+ ):
+ 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 {}
+
output_path: Optional[str] = None
model_tmp_to_cleanup: Optional[str] = None
try:
@@ -691,6 +774,7 @@ class ExportBackend:
_model_tmp,
self.current_tokenizer,
quantization_method = quant_method,
+ **imatrix_kw,
)
# Relocate the .gguf that convert_to_gguf wrote to cwd (repo root).
@@ -757,6 +841,7 @@ class ExportBackend:
self.current_tokenizer,
quantization_method = quant_method,
token = hf_token,
+ **imatrix_kw,
)
logger.info(f"GGUF model pushed successfully to {repo_id}")
diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py
index 478624b48e3..052a47dd807 100644
--- a/studio/backend/core/export/orchestrator.py
+++ b/studio/backend/core/export/orchestrator.py
@@ -499,6 +499,7 @@ class ExportOrchestrator:
push_to_hub: bool = False,
repo_id: Optional[str] = None,
hf_token: Optional[str] = None,
+ imatrix_file = None,
) -> Tuple[bool, str, Optional[str]]:
"""Export model in GGUF format."""
return self._run_export(
@@ -509,6 +510,7 @@ class ExportOrchestrator:
"push_to_hub": push_to_hub,
"repo_id": repo_id,
"hf_token": hf_token,
+ "imatrix_file": imatrix_file,
},
)
diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py
index 71a603a8571..d473dcb54f0 100644
--- a/studio/backend/core/export/worker.py
+++ b/studio/backend/core/export/worker.py
@@ -414,6 +414,7 @@ def _handle_export(backend, cmd: dict, resp_queue: Any) -> None:
push_to_hub = cmd.get("push_to_hub", False),
repo_id = cmd.get("repo_id"),
hf_token = cmd.get("hf_token"),
+ imatrix_file = cmd.get("imatrix_file"),
)
elif export_type == "lora":
success, message, output_path = backend.export_lora_adapter(
diff --git a/studio/backend/models/export.py b/studio/backend/models/export.py
index 1e8e3c4792b..7e05373f110 100644
--- a/studio/backend/models/export.py
+++ b/studio/backend/models/export.py
@@ -158,9 +158,15 @@ class ExportCommonOptions(BaseModel):
class ExportMergedModelRequest(ExportCommonOptions):
"""Request for exporting a merged PEFT model."""
- format_type: Literal["16-bit (FP16)", "4-bit (FP4)"] = Field(
+ format_type: Literal[
"16-bit (FP16)",
- description = "Export precision / format for the merged model",
+ "4-bit (FP4)",
+ "FP8 (compressed-tensors)",
+ "NVFP4 (compressed-tensors)",
+ ] = Field(
+ "16-bit (FP16)",
+ description = "Export precision / format for the merged model. The compressed-tensors "
+ "options run llm-compressor for vLLM (FP8 is data-free; NVFP4 calibrates).",
)
@@ -199,6 +205,15 @@ class ExportGGUFRequest(BaseModel):
None,
description = "Hugging Face token for GGUF upload",
)
+ imatrix: bool = Field(
+ False,
+ description = "Use an importance matrix (auto-downloads the upstream unsloth GGUF "
+ "imatrix). Required for the IQ low-bit quants such as iq2_xxs / iq4_xs.",
+ )
+ imatrix_path: Optional[str] = Field(
+ None,
+ description = "Path to a custom imatrix file; overrides the auto-download when set.",
+ )
class ExportLoRAAdapterRequest(ExportCommonOptions):
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index 78c1e59d2e5..cf2cb2fa705 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -343,6 +343,8 @@ async def export_gguf(
"""
try:
backend = get_export_backend()
+ # A custom path wins; otherwise the imatrix toggle requests the upstream auto-download.
+ imatrix_file = request.imatrix_path or (True if request.imatrix else None)
success, message, output_path = await asyncio.to_thread(
backend.export_gguf,
save_directory = request.save_directory,
@@ -350,6 +352,7 @@ async def export_gguf(
push_to_hub = request.push_to_hub,
repo_id = request.repo_id,
hf_token = request.hf_token,
+ imatrix_file = imatrix_file,
)
if not success:
diff --git a/studio/backend/tests/test_export_imatrix_compressed.py b/studio/backend/tests/test_export_imatrix_compressed.py
new file mode 100644
index 00000000000..d914ff8651e
--- /dev/null
+++ b/studio/backend/tests/test_export_imatrix_compressed.py
@@ -0,0 +1,116 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the GGUF imatrix option and compressed-tensors merged export wiring.
+
+Schema checks use the real Pydantic models; the cross-layer threading is verified with ast so it
+runs on CPU with no GPU, no model, and no llama.cpp.
+"""
+
+import ast
+from pathlib import Path
+
+import pytest
+from pydantic import ValidationError
+
+from models.export import ExportGGUFRequest, ExportMergedModelRequest
+
+_BACKEND = Path(__file__).resolve().parent.parent
+
+
+def _src(rel):
+ return (_BACKEND / rel).read_text(encoding = "utf-8")
+
+
+def _func_src(rel, name):
+ src = _src(rel)
+ node = next(
+ n for n in ast.walk(ast.parse(src)) if isinstance(n, ast.FunctionDef) and n.name == name
+ )
+ return ast.get_source_segment(src, node)
+
+
+# -- schema -------------------------------------------------------------------------------------
+
+
+def test_gguf_request_imatrix_defaults_and_set():
+ assert ExportGGUFRequest(save_directory = "/tmp/x").imatrix is False
+ assert ExportGGUFRequest(save_directory = "/tmp/x").imatrix_path is None
+ r = ExportGGUFRequest(save_directory = "/tmp/x", imatrix = True, imatrix_path = "/i.dat")
+ assert r.imatrix is True and r.imatrix_path == "/i.dat"
+
+
+def test_merged_request_accepts_compressed_formats():
+ for fmt in ("16-bit (FP16)", "FP8 (compressed-tensors)", "NVFP4 (compressed-tensors)"):
+ assert ExportMergedModelRequest(save_directory = "/tmp/x", format_type = fmt).format_type == fmt
+
+
+def test_merged_request_rejects_unknown_format():
+ with pytest.raises(ValidationError):
+ ExportMergedModelRequest(save_directory = "/tmp/x", format_type = "bogus")
+
+
+# -- threading (ast) ----------------------------------------------------------------------------
+
+
+def test_export_gguf_threads_imatrix_to_save_and_push():
+ # imatrix_file must reach both save_pretrained_gguf and push_to_hub_gguf, but only via the
+ # conditional **imatrix_kw so a no-imatrix export never sends an unsupported keyword.
+ 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
+ # 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.
+ g = _func_src("core/export/export.py", "export_gguf")
+ assert "_supports_kwarg(" in g and '"imatrix_file"' in g
+
+
+def test_export_merged_guards_unsupported_compressed_build():
+ m = _func_src("core/export/export.py", "export_merged_model")
+ assert "_compressed_export_supported()" in m
+
+
+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)
+ supports = ns["_supports_kwarg"]
+
+ def has_it(a, imatrix_file = None):
+ pass
+
+ def lacks_it(a):
+ pass
+
+ def via_kwargs(a, **kw):
+ pass
+
+ assert supports(has_it, "imatrix_file") is True
+ assert supports(lacks_it, "imatrix_file") is False
+ assert supports(via_kwargs, "imatrix_file") is True
+
+
+def test_orchestrator_and_worker_pass_imatrix():
+ assert "imatrix_file" in _func_src("core/export/orchestrator.py", "export_gguf")
+ assert 'imatrix_file = cmd.get("imatrix_file")' in _src("core/export/worker.py")
+
+
+def test_route_resolves_imatrix_file():
+ assert "request.imatrix_path or (True if request.imatrix else None)" in _src("routes/export.py")
+
+
+def test_export_merged_maps_compressed_to_save_method():
+ m = _func_src("core/export/export.py", "export_merged_model")
+ assert "is_compressed" in m and '"fp8"' in m and '"nvfp4"' in m
+
+
+def test_compressed_hub_push_uploads_local_dir_without_recompressing():
+ # A compressed Hub push must upload the already-built output_path, not re-run compression
+ # via push_to_hub_merged (which would compress a second time).
+ m = _func_src("core/export/export.py", "export_merged_model")
+ assert "elif is_compressed and output_path and Path(output_path).is_dir():" in m
+ assert "hf_api.upload_folder(" in m and "folder_path = output_path" in m
diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.ts
index f055f1bd618..d1b4e88a6df 100644
--- a/studio/frontend/src/features/export/api/export-api.ts
+++ b/studio/frontend/src/features/export/api/export-api.ts
@@ -162,6 +162,8 @@ export async function exportGGUF(params: {
push_to_hub?: boolean;
repo_id?: string | null;
hf_token?: string | null;
+ imatrix?: boolean;
+ imatrix_path?: string | null;
}): Promise<ExportOperationResponse> {
const response = await authFetch("/api/export/export/gguf", {
method: "POST",
diff --git a/studio/frontend/src/features/export/constants.ts b/studio/frontend/src/features/export/constants.ts
index 9b7e487450a..058de1edc42 100644
--- a/studio/frontend/src/features/export/constants.ts
+++ b/studio/frontend/src/features/export/constants.ts
@@ -39,7 +39,12 @@ export const QUANT_OPTIONS: {
value: string;
label: string;
recommended?: boolean;
+ imatrix?: boolean; // IQ quants require an importance matrix (the imatrix toggle below)
}[] = [
+ { value: "iq2_xxs", label: "IQ2_XXS", imatrix: true },
+ { value: "iq2_m", label: "IQ2_M", imatrix: true },
+ { value: "iq3_xxs", label: "IQ3_XXS", imatrix: true },
+ { value: "iq4_xs", label: "IQ4_XS", imatrix: true },
{ value: "q2_k_l", label: "Q2_K_L" },
{ value: "q3_k_m", label: "Q3_K_M" },
{ value: "q4_k_m", label: "Q4_K_M", recommended: true },
@@ -50,12 +55,44 @@ export const QUANT_OPTIONS: {
{ value: "f16", label: "F16" },
];
+/** Merged-export precision formats. The compressed-tensors ones run llm-compressor for vLLM. */
+export type MergedFormat =
+ | "16-bit (FP16)"
+ | "FP8 (compressed-tensors)"
+ | "NVFP4 (compressed-tensors)";
+
+export const MERGED_FORMATS: {
+ value: MergedFormat;
+ label: string;
+ hint: string;
+}[] = [
+ {
+ value: "16-bit (FP16)",
+ label: "16-bit",
+ hint: "Full precision, runs anywhere.",
+ },
+ {
+ value: "FP8 (compressed-tensors)",
+ label: "FP8 (vLLM)",
+ hint: "compressed-tensors FP8 for vLLM. Needs an NVIDIA GPU.",
+ },
+ {
+ value: "NVFP4 (compressed-tensors)",
+ label: "NVFP4 (vLLM)",
+ hint: "compressed-tensors NVFP4 for vLLM. Needs an NVIDIA GPU; calibrates.",
+ },
+];
+
/**
* llama.cpp effective bits-per-weight per quant; GGUF size ~= fp16_bytes * bpw / 16.
* K-quant values are published average bit-rates (Q2_K_L = Unsloth Q2_K + Q8_0
* embeddings). Approximate ("~"), not exact file sizes.
*/
export const GGUF_BPW: Record<string, number> = {
+ iq2_xxs: 2.06,
+ iq2_m: 2.7,
+ iq3_xxs: 3.06,
+ iq4_xs: 4.25,
q2_k_l: 3.35,
q3_k_m: 3.91,
q4_k_m: 4.83,
diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsx
index 4037dbe0793..7b5c6ec6d41 100644
--- a/studio/frontend/src/features/export/export-page.tsx
+++ b/studio/frontend/src/features/export/export-page.tsx
@@ -3,6 +3,7 @@
import { SectionCard } from "@/components/section-card";
import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
import {
Combobox,
ComboboxContent,
@@ -61,6 +62,9 @@ import {
EXPORT_METHODS,
type ExportMethod,
GUIDE_STEPS,
+ MERGED_FORMATS,
+ type MergedFormat,
+ QUANT_OPTIONS,
buildQuantSizeLabels,
getEstimatedSize,
} from "./constants";
@@ -171,6 +175,16 @@ export function ExportPage() {
? s.summary.quantLevels
: [];
});
+ // GGUF importance matrix (required for the IQ quants) and merged-export precision.
+ const [useImatrix, setUseImatrix] = useState(false);
+ const [mergedFormat, setMergedFormat] = useState<MergedFormat>("16-bit (FP16)");
+ // IQ quants are imatrix-only, so force it on when one is selected; otherwise we would submit
+ // an IQ quant with no imatrix and llama.cpp would reject it.
+ const requiresImatrix = quantLevels.some(
+ (q) => QUANT_OPTIONS.find((o) => o.value === q)?.imatrix,
+ );
+ const effectiveImatrix = useImatrix || requiresImatrix;
+
// Whether the inline export panel is expanded. The panel also shows itself
// whenever a run is active/terminal (see `panelActive`), so it survives
// navigation even though this local flag resets on remount.
@@ -613,6 +627,8 @@ export function ExportPage() {
exportMethod,
isAdapter: adapterExport,
quantLevels,
+ useImatrix: effectiveImatrix,
+ mergedFormat,
saveDirectory,
destination,
repoId,
@@ -639,6 +655,8 @@ export function ExportPage() {
exportMethod,
isAdapter,
quantLevels,
+ effectiveImatrix,
+ mergedFormat,
destination,
saveDirectory,
hfUsername,
@@ -1166,12 +1184,54 @@ export function ExportPage() {
}
/>
+ {exportMethod === "merged" && isAdapter && (
+ <div className="space-y-2">
+ <div className="text-sm font-medium">Precision</div>
+ <div className="flex flex-wrap gap-2">
+ {MERGED_FORMATS.map((f) => (
+ <Button
+ key={f.value}
+ type="button"
+ variant={mergedFormat === f.value ? "default" : "outline"}
+ size="sm"
+ onClick={() => setMergedFormat(f.value)}
+ title={f.hint}
+ >
+ {f.label}
+ </Button>
+ ))}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {MERGED_FORMATS.find((f) => f.value === mergedFormat)?.hint}
+ </div>
+ </div>
+ )}
+
{exportMethod === "gguf" && (
- <QuantPicker
- value={quantLevels}
- onChange={setQuantLevels}
- sizes={quantSizeLabels}
- />
+ <>
+ <QuantPicker
+ value={quantLevels}
+ onChange={setQuantLevels}
+ sizes={quantSizeLabels}
+ />
+ <div className="flex items-center justify-between gap-3 rounded-lg border p-3">
+ <div className="space-y-0.5">
+ <div className="text-sm font-medium">
+ Importance matrix (imatrix)
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {requiresImatrix
+ ? "Required for the selected IQ low-bit quant. Auto-downloads the upstream Unsloth imatrix for the base model."
+ : "Improves quant quality and unlocks the IQ low-bit quants. Auto-downloads the upstream Unsloth imatrix for the base model."}
+ </div>
+ </div>
+ <Switch
+ checked={effectiveImatrix}
+ onCheckedChange={setUseImatrix}
+ disabled={requiresImatrix}
+ />
+ </div>
+ </>
)}
{estimatedSize && (
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
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 307e1ccaabf..a87e7d93e99 100644
--- a/studio/frontend/src/features/export/stores/export-runtime-store.ts
+++ b/studio/frontend/src/features/export/stores/export-runtime-store.ts
@@ -138,6 +138,10 @@ export interface RunExportParams {
exportMethod: ExportMethod;
isAdapter: boolean;
quantLevels: string[];
+ /** GGUF: use an importance matrix (auto-download); required for the IQ quants. */
+ useImatrix?: boolean;
+ /** Merged: precision/format ("16-bit (FP16)" or a compressed-tensors option). */
+ mergedFormat?: string;
saveDirectory: string;
destination: ExportDestination;
repoId?: string;
@@ -437,6 +441,7 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
const { outputPath } = await runRecoverableOp(() =>
exportMerged({
save_directory: params.saveDirectory,
+ format_type: params.mergedFormat,
push_to_hub: pushToHub,
repo_id: params.repoId,
hf_token: params.token,
@@ -469,6 +474,7 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
push_to_hub: pushToHub,
repo_id: params.repoId,
hf_token: params.token,
+ imatrix: params.useImatrix,
}),
);
lastOutputPath = outputPath ?? lastOutputPath;