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: Export a full fine-tune as a real 16-bit model (#10808)

Nilay3a5a8513a7e0
diff --git a/studio/backend/mcp_server.py b/studio/backend/mcp_server.py
index 20bac30bde4..b18d4d17a16 100644
--- a/studio/backend/mcp_server.py
+++ b/studio/backend/mcp_server.py
@@ -192,7 +192,7 @@ def create_studio_mcp() -> FastMCP:
async def load_checkpoint(
checkpoint_path: str,
max_seq_length: int = 2048,
- load_in_4bit: bool = True,
+ load_in_4bit: bool | None = None,
trust_remote_code: bool = False,
approved_remote_code_fingerprint: str | None = None,
hf_token: str | None = None,
@@ -203,18 +203,22 @@ def create_studio_mcp() -> FastMCP:
inference; it does not unload them, so a load can fail with a clear
out-of-memory error if the GPU is already full. Pass hf_token to load a
gated checkpoint, and approved_remote_code_fingerprint to retry a
- trust_remote_code load that was blocked pending review.
+ trust_remote_code load that was blocked pending review. Leave
+ load_in_4bit unset to load full fine-tunes in 16-bit and adapters in
+ 4-bit.
"""
from models import LoadCheckpointRequest
from routes.export import load_checkpoint as load
+ # Omit an unset load_in_4bit so the route can pick 16-bit for a full fine-tune.
+ optional = {} if load_in_4bit is None else {"load_in_4bit": load_in_4bit}
request = LoadCheckpointRequest(
checkpoint_path = checkpoint_path,
max_seq_length = max_seq_length,
- load_in_4bit = load_in_4bit,
trust_remote_code = trust_remote_code,
approved_remote_code_fingerprint = approved_remote_code_fingerprint,
hf_token = hf_token,
+ **optional,
)
return _dump(await load(request, current_subject = "mcp", allow_ambient = False))
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index 0f7aa91a978..c6dfcf08441 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -111,6 +111,54 @@ def _authorized_adapter_base(checkpoint_path: str) -> Optional[str]:
return base or None
+def _hub_config(repo_id: str, hf_token: HfTokenArg) -> Optional[dict]:
+ """config.json for a Hub repo id, or None when it cannot be resolved.
+
+ The worker loads remote checkpoints too, so a Hub id that never touches the local
+ filesystem would otherwise keep the 4-bit default and re-introduce the very export
+ this function exists to prevent. Only config.json is fetched -- a few KB against the
+ gigabytes the load is about to pull anyway, and cached by huggingface_hub after the
+ first call.
+
+ Every failure (offline, gated without a token, no such repo, no network) returns
+ None, which the caller reads as "unknown" and leaves on the historical default.
+ """
+ try:
+ from huggingface_hub import file_exists, hf_hub_download
+
+ # An adapter repo carries a base config.json as well, so this has to be asked
+ # first or a remote LoRA reads as a full model.
+ if file_exists(repo_id, "adapter_config.json", token = hf_token):
+ return None
+ path = hf_hub_download(repo_id, "config.json", token = hf_token)
+ return json.loads(Path(path).read_text(encoding = "utf-8-sig"))
+ except Exception:
+ return None
+
+
+def _is_unquantized_full_finetune(checkpoint_path: str, hf_token: HfTokenArg = None) -> bool:
+ """Whether this checkpoint is a full model that is not already quantized.
+
+ Only ever used to turn 4-bit OFF, so every uncertain answer here is False and
+ behaves exactly as the code did before.
+ """
+ checkpoint_dir = Path(checkpoint_path)
+ config_file = checkpoint_dir / "config.json"
+ try:
+ if config_file.is_file():
+ if (checkpoint_dir / "adapter_config.json").exists():
+ return False
+ config = json.loads(config_file.read_text(encoding = "utf-8-sig"))
+ elif checkpoint_dir.exists():
+ # A local directory without a config.json is not a full model.
+ return False
+ else:
+ config = _hub_config(checkpoint_path, hf_token)
+ except (OSError, ValueError):
+ return False
+ return isinstance(config, dict) and "quantization_config" not in config
+
+
@router.post("/load-checkpoint", response_model = ExportOperationResponse)
async def load_checkpoint(
request: LoadCheckpointRequest,
@@ -128,6 +176,18 @@ async def load_checkpoint(
base_model = await asyncio.to_thread(_authorized_adapter_base, request.checkpoint_path)
try:
await _ensure_export_supported()
+ export_hf_token = _resolve_export_hf_token(request.hf_token, allow_ambient = allow_ambient)
+ load_in_4bit = request.load_in_4bit
+ # Off-loop: a Hub id makes this reach the network, and the SSE log stream is
+ # served from this same event loop.
+ if "load_in_4bit" not in request.model_fields_set and await asyncio.to_thread(
+ _is_unquantized_full_finetune, request.checkpoint_path, export_hf_token
+ ):
+ load_in_4bit = False
+ logger.info(
+ f"Full fine-tune checkpoint {request.checkpoint_path} has no quantization_config - "
+ "loading in 16-bit for export"
+ )
backend = get_export_backend()
# Run in a worker thread (spawns and waits on a subprocess, can take
# minutes) so the event loop stays free to serve the live log SSE stream.
@@ -136,10 +196,10 @@ async def load_checkpoint(
checkpoint_path = request.checkpoint_path,
base_model = base_model,
max_seq_length = request.max_seq_length,
- load_in_4bit = request.load_in_4bit,
+ load_in_4bit = load_in_4bit,
trust_remote_code = request.trust_remote_code,
approved_remote_code_fingerprint = request.approved_remote_code_fingerprint,
- hf_token = _resolve_export_hf_token(request.hf_token, allow_ambient = allow_ambient),
+ hf_token = export_hf_token,
# A supplied token cannot say whether it came from a session or an API key.
allow_ambient = allow_ambient,
subject = current_subject,
diff --git a/studio/backend/tests/test_export_load_checkpoint_full_finetune.py b/studio/backend/tests/test_export_load_checkpoint_full_finetune.py
new file mode 100644
index 00000000000..c0bbd3ba0a8
--- /dev/null
+++ b/studio/backend/tests/test_export_load_checkpoint_full_finetune.py
@@ -0,0 +1,139 @@
+# 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 json
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import allow_ambient_hf_token, get_current_subject
+from routes import export as export_routes
+
+
+async def _fake_ensure_export_supported():
+ pass
+
+
+_FULL_FINETUNE = {"config.json": {"model_type": "llama"}}
+_LORA_ADAPTER = {
+ "config.json": {"model_type": "llama"},
+ "adapter_config.json": {"base_model_name_or_path": "unsloth/Llama-3.2-1B"},
+}
+_BNB_QUANTIZED = {
+ "config.json": {
+ "model_type": "llama",
+ "quantization_config": {"quant_method": "bitsandbytes", "load_in_4bit": True},
+ }
+}
+_MALFORMED_CONFIG = {"config.json": "{not json"}
+
+
+ "files,extra,expected",
+ [
+ (_FULL_FINETUNE, {}, False),
+ (_FULL_FINETUNE, {"load_in_4bit": True}, True),
+ (_LORA_ADAPTER, {}, True),
+ (_BNB_QUANTIZED, {}, True),
+ (_MALFORMED_CONFIG, {}, True),
+ ],
+ ids = [
+ "full_finetune",
+ "full_finetune_explicit_4bit",
+ "lora_adapter",
+ "bnb_quantized",
+ "malformed_config",
+ ],
+)
+def test_load_checkpoint_uses_16bit_for_unquantized_full_finetunes(
+ monkeypatch, tmp_path, files, extra, expected
+):
+ for name, content in files.items():
+ text = content if isinstance(content, str) else json.dumps(content)
+ (tmp_path / name).write_text(text, encoding = "utf-8")
+
+ monkeypatch.setattr(export_routes, "_ensure_export_supported", _fake_ensure_export_supported)
+ backend = MagicMock()
+ backend.load_checkpoint.return_value = (True, "loaded")
+ monkeypatch.setattr(export_routes, "get_export_backend", lambda: backend)
+
+ app = FastAPI()
+ app.include_router(export_routes.router, prefix = "/api/export")
+ app.dependency_overrides[get_current_subject] = lambda: "alice"
+ app.dependency_overrides[allow_ambient_hf_token] = lambda: True
+
+ response = TestClient(app).post(
+ "/api/export/load-checkpoint",
+ json = {"checkpoint_path": str(tmp_path), "hf_token": None, **extra},
+ )
+
+ assert response.status_code == 200
+ assert backend.load_checkpoint.call_args.kwargs["load_in_4bit"] is expected
+
+
+def _hub_client(monkeypatch, backend):
+ monkeypatch.setattr(export_routes, "_ensure_export_supported", _fake_ensure_export_supported)
+ monkeypatch.setattr(export_routes, "get_export_backend", lambda: backend)
+ app = FastAPI()
+ app.include_router(export_routes.router, prefix = "/api/export")
+ app.dependency_overrides[get_current_subject] = lambda: "alice"
+ app.dependency_overrides[allow_ambient_hf_token] = lambda: True
+ return TestClient(app)
+
+
+ "adapter_on_hub,hub_config,expected",
+ [
+ (False, {"model_type": "llama"}, False),
+ (
+ False,
+ {"model_type": "llama", "quantization_config": {"quant_method": "bitsandbytes"}},
+ True,
+ ),
+ (True, {"model_type": "llama"}, True),
+ ],
+ ids = ["remote_full_finetune", "remote_bnb_quantized", "remote_lora_adapter"],
+)
+def test_load_checkpoint_resolves_hub_ids_before_choosing_4bit(
+ monkeypatch, tmp_path, adapter_on_hub, hub_config, expected
+):
+ """A Hub id never touches the local filesystem, so without this the request keeps the
+ request model's True default and a remote full fine-tune exports as 4-bit anyway."""
+ config_file = tmp_path / "config.json"
+ config_file.write_text(json.dumps(hub_config), encoding = "utf-8")
+
+ monkeypatch.setattr(
+ export_routes,
+ "_hub_config",
+ lambda repo_id, hf_token: None if adapter_on_hub else hub_config,
+ )
+ backend = MagicMock()
+ backend.load_checkpoint.return_value = (True, "loaded")
+
+ response = _hub_client(monkeypatch, backend).post(
+ "/api/export/load-checkpoint",
+ json = {"checkpoint_path": "unsloth/Llama-3.2-1B-Instruct", "hf_token": None},
+ )
+
+ assert response.status_code == 200
+ assert backend.load_checkpoint.call_args.kwargs["load_in_4bit"] is expected
+
+
+def test_hub_lookup_failure_keeps_the_old_default(monkeypatch):
+ """Offline, gated without a token, or no such repo: fail OPEN to the historical 4-bit
+ default rather than guessing 16-bit and OOMing a load that used to fit."""
+
+ def _boom(
+ repo_id,
+ filename,
+ token = None,
+ ):
+ raise OSError("no network")
+
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "file_exists", _boom, raising = False)
+ assert export_routes._hub_config("org/model", None) is None
+ assert export_routes._is_unquantized_full_finetune("org/model", None) is False
diff --git a/studio/backend/tests/test_mcp_server.py b/studio/backend/tests/test_mcp_server.py
index 30e90b2fb32..968af081fa2 100644
--- a/studio/backend/tests/test_mcp_server.py
+++ b/studio/backend/tests/test_mcp_server.py
@@ -264,6 +264,30 @@ def test_load_checkpoint_forwards_token_and_fingerprint(monkeypatch):
assert result["allow_ambient"] is False
[email protected]("load_in_4bit", [None, True, False])
+def test_load_checkpoint_leaves_unset_load_in_4bit_to_the_route(monkeypatch, load_in_4bit):
+ from models.export import LoadCheckpointRequest
+
+ captured = {}
+
+ async def fake_load(request, current_subject, allow_ambient):
+ captured["fields_set"] = request.model_fields_set
+ captured["load_in_4bit"] = request.load_in_4bit
+ return {}
+
+ _stub_module(monkeypatch, "models", LoadCheckpointRequest = LoadCheckpointRequest)
+ _stub_module(monkeypatch, "routes")
+ _stub_module(monkeypatch, "routes.export", load_checkpoint = fake_load)
+
+ extra = {} if load_in_4bit is None else {"load_in_4bit": load_in_4bit}
+ asyncio.run(_get_tool("load_checkpoint").fn(checkpoint_path = "/tmp/ckpt", **extra))
+
+ # The route only picks 16-bit for a full fine-tune when load_in_4bit was not sent.
+ assert ("load_in_4bit" in captured["fields_set"]) is (load_in_4bit is not None)
+ if load_in_4bit is not None:
+ assert captured["load_in_4bit"] is load_in_4bit
+
+
def test_stop_training_forwards_job_scope(monkeypatch):
captured = {}