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: default export load to offload_layers=auto (#13720)
Indrajit swain7844d9c63122
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 98ec9cbe6de..7a4169efa72 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -88,6 +88,22 @@ def _load_in_4bit_kwargs(load_in_4bit: bool) -> dict:return {} if load_in_4bit else {"load_in_4bit": False}+# Export merges one module at a time and trains nothing, so the auto plan keeps 1 GiB for that, not a training step.+_EXPORT_AUTO_OFFLOAD_KWARGS = {+ "offload_layers": "auto",+ "device_map_planner_kwargs": {"reserve_bytes": 1 << 30},+}+++def _offload_layers_kwargs(offload_layers, device_map_kw: Optional[dict] = None) -> dict:+ if not offload_layers or offload_layers == "auto":+ return {}+ # A fixed count loads onto one card; core raises on a multi-GPU map.+ if (device_map_kw or {}).get("device_map") in ("unsloth_balanced", "balanced"):+ return {}+ return {"offload_layers": offload_layers}++def _export_runtime_available() -> bool:"""True if export can run: MLX active, or Unsloth imported (only succeeds on a GPU host)."""return bool(_IS_MLX) or (FastLanguageModel is not None)@@ -245,9 +261,14 @@ def _is_cpu_spill_rejection(exc: BaseException) -> bool:Busy secondary GPUs can make ``balanced`` spill to CPU even where the old sequentialload fit on GPU0, and that message says nothing about memory, so the retry has to- match it explicitly. See transformers ``quantizers/quantizer_bnb_4bit.py``.+ match it explicitly. See transformers ``quantizers/quantizer_bnb_4bit.py``. Unsloth+ re-raises it as "does not fit in GPU memory" with the original as ``__cause__``."""- return "dispatched on the cpu or the disk" in str(exc).lower()+ while exc is not None:+ if "dispatched on the cpu or the disk" in str(exc).lower():+ return True+ exc = exc.__cause__+ return Falsedef _is_device_map_infeasible(exc: BaseException) -> bool:@@ -767,6 +788,8 @@ class ExportBackend:hf_token: HfTokenArg = None,_device_map_override: Optional[dict] = None,base_model: Optional[str] = None,+ offload_layers = "auto",+ _offload_retry: bool = False,) -> Tuple[bool, str]:"""Load a checkpoint for export.@@ -776,6 +799,8 @@ class ExportBackend:the token the worker used for the security preflight (otherwise a gated repo passes scanningthen 401s at from_pretrained).+ ``offload_layers = "auto"`` only retries a single-GPU 4-bit load that spilled to the CPU (#13696).+``False`` (denied the ambient token) must travel all the way down: ``None`` reads as "go andfind a credential" (``if token is None: get_token()`` in ``save.py`` and ``hf_login``), and``get_token()`` reads the operator's stored login off disk.@@ -823,6 +848,11 @@ class ExportBackend:if _device_map_override is Noneelse _device_map_override)+ _offload_kw = (+ _EXPORT_AUTO_OFFLOAD_KWARGS+ if _offload_retry+ else _offload_layers_kwargs(offload_layers, _device_map_kw)+ )# Run the type-detection probes inside the forced-offline window, else a gated base 404s: it# covers is_vision_model's Hub reads, and local_files_only makes detect_audio_type's requests.get@@ -862,6 +892,7 @@ class ExportBackend:token = token,local_files_only = local_files_only,**_device_map_kw,+ **_offload_kw,)elif self._audio_type == "whisper":@@ -880,6 +911,7 @@ class ExportBackend:token = token,local_files_only = local_files_only,**_device_map_kw,+ **_offload_kw,)elif self._audio_type == "snac":@@ -893,6 +925,7 @@ class ExportBackend:token = token,local_files_only = local_files_only,**_device_map_kw,+ **_offload_kw,)elif self._audio_type == "bicodec":@@ -912,6 +945,7 @@ class ExportBackend:token = token,local_files_only = local_files_only,**_device_map_kw,+ **_offload_kw,)elif self._audio_type == "dac":@@ -925,11 +959,13 @@ class ExportBackend:token = token,local_files_only = local_files_only,**_device_map_kw,+ **_offload_kw,)elif self.diffusion_lm_profile:from unsloth import FastModellogger.info(f"Loading as text-diffusion model ({self.diffusion_lm_profile})...")+ # Text-diffusion has no block swapping; skip offload like Training does.model, tokenizer = FastModel.from_pretrained(model_name = checkpoint_path,max_seq_length = max_seq_length,@@ -952,6 +988,7 @@ class ExportBackend:token = token,local_files_only = local_files_only,**_device_map_kw,+ **_offload_kw,)tokenizer = processor@@ -966,6 +1003,7 @@ class ExportBackend:token = token,local_files_only = local_files_only,**_device_map_kw,+ **_offload_kw,)if _IS_MLX and adapter_config.exists():tokenizer = load_mlx_adapter_tokenizer(tokenizer, checkpoint_path)@@ -1029,6 +1067,19 @@ class ExportBackend:# Retry outside this block: the live traceback pins the half-built model's frames, so an in-block# retry inherits the exhausted device.retry_reason = str(e)+ # Name the map: an omitted one is unsloth's DEFAULT_DEVICE_MAP, which requested_device_map+ # upgrades back to the planner, re-running the placement that just failed.+ retry_kw = {"_device_map_override": {"device_map": "sequential"}}+ elif (+ offload_layers == "auto"+ and not _offload_retry+ and _device_map_override is None+ and not self.diffusion_lm_profile+ and _is_cpu_spill_rejection(e)+ and not _multi_gpu_device_map_kwargs()+ ):+ retry_reason = str(e)+ retry_kw = {"_offload_retry": True}else:logger.error(f"Error loading checkpoint: {e}")import traceback@@ -1036,20 +1087,26 @@ class ExportBackend:logger.error(traceback.format_exc())return False, f"Failed to load checkpoint: {str(e)}"- logger.warning(- f"Multi-GPU export load unusable ({retry_reason}); retrying on "- f"the sequential loader default."- )+ if "_offload_retry" in retry_kw:+ logger.warning(+ f"Export load does not fit in GPU memory ({retry_reason}); retrying with "+ f"offload_layers='auto' to keep the layers the GPU cannot hold in host RAM."+ )+ else:+ logger.warning(+ f"Multi-GPU export load unusable ({retry_reason}); retrying on "+ f"the sequential loader default."+ )self.cleanup_memory()return self.load_checkpoint(checkpoint_path,max_seq_length = max_seq_length,load_in_4bit = load_in_4bit,+ offload_layers = offload_layers,trust_remote_code = trust_remote_code,hf_token = hf_token,- # Name the map: an omitted one is unsloth's DEFAULT_DEVICE_MAP, which requested_device_map- # upgrades back to the planner, re-running the placement that just failed.- _device_map_override = {"device_map": "sequential"},+ base_model = base_model,+ **retry_kw,)def _load_decision_checkpoint(diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.pyindex 6836b828a06..64f903951d9 100644--- a/studio/backend/core/export/orchestrator.py+++ b/studio/backend/core/export/orchestrator.py@@ -524,6 +524,7 @@ class ExportOrchestrator:subject: Optional[str] = None,base_model: Optional[str] = None,op_id: Optional[str] = None,+ offload_layers = "auto",) -> Tuple[bool, str]:"""Load a checkpoint for export.@@ -547,6 +548,7 @@ class ExportOrchestrator:"base_model": base_model,"max_seq_length": max_seq_length,"load_in_4bit": load_in_4bit,+ "offload_layers": offload_layers,"trust_remote_code": trust_remote_code,"approved_remote_code_fingerprint": approved_remote_code_fingerprint,"subject": subject,diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.pyindex e0f1e87be39..53754e39189 100644--- a/studio/backend/core/export/worker.py+++ b/studio/backend/core/export/worker.py@@ -377,6 +377,7 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:checkpoint_path = checkpoint_path,max_seq_length = max_seq_length,load_in_4bit = load_in_4bit,+ offload_layers = cmd.get("offload_layers", "auto"),trust_remote_code = trust_remote_code,hf_token = hf_token,base_model = base_model,diff --git a/studio/backend/models/export.py b/studio/backend/models/export.pyindex 69281b599c7..fdadb687edc 100644--- a/studio/backend/models/export.py+++ b/studio/backend/models/export.py@@ -6,7 +6,7 @@from pathlib import Path, PureWindowsPathfrom pydantic import BaseModel, Field, field_validator-from typing import List, Optional, Literal, Dict, Any, Union+from typing import Annotated, List, Optional, Literal, Dict, Any, Uniondef _validate_save_directory(value: str) -> str:@@ -47,6 +47,11 @@ class LoadCheckpointRequest(BaseModel):True,description = "Whether to load the model in 4-bit quantization",)+ offload_layers: Union[Literal["auto"], Annotated[int, Field(ge = 0, le = 1024)]] = Field(+ "auto",+ description = "Decoder layers kept in host RAM and streamed to the GPU during export "+ "(0 = off; 'auto' = only when a 4-bit load does not fit in GPU memory).",+ )trust_remote_code: bool = Field(False,description = "Allow loading models with custom code. Only enable for checkpoints/base models you trust.",diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex 3dd58212e84..5e687d519a9 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -146,6 +146,7 @@ async def load_checkpoint(base_model = base_model,max_seq_length = request.max_seq_length,load_in_4bit = load_in_4bit,+ offload_layers = request.offload_layers,trust_remote_code = request.trust_remote_code,approved_remote_code_fingerprint = request.approved_remote_code_fingerprint,hf_token = export_hf_token,diff --git a/studio/backend/tests/test_export_load_checkpoint_full_finetune.py b/studio/backend/tests/test_export_load_checkpoint_full_finetune.pyindex 87dbe419ede..317b29b4fab 100644--- a/studio/backend/tests/test_export_load_checkpoint_full_finetune.py+++ b/studio/backend/tests/test_export_load_checkpoint_full_finetune.py@@ -154,6 +154,27 @@ def test_route_leaves_unset_load_in_4bit_to_the_backend(monkeypatch, tmp_path, eassert backend.load_checkpoint.call_args.kwargs["load_in_4bit"] is expected+def test_route_defaults_offload_layers_to_auto(monkeypatch, tmp_path):+ """#13696: Output export load defaults offload_layers='auto' without a UI control."""+ 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},+ )++ assert response.status_code == 200+ assert backend.load_checkpoint.call_args.kwargs["offload_layers"] == "auto"++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-bitdefault rather than guessing 16-bit and OOMing a load that used to fit."""diff --git a/studio/backend/tests/test_export_multi_gpu_device_map.py b/studio/backend/tests/test_export_multi_gpu_device_map.pyindex df58e90669f..5cc6747e478 100644--- a/studio/backend/tests/test_export_multi_gpu_device_map.py+++ b/studio/backend/tests/test_export_multi_gpu_device_map.py@@ -160,6 +160,127 @@ def test_load_checkpoint_omits_device_map_on_single_gpu(monkeypatch, tmp_path):assert "device_map" not in kwargs # loader default (sequential) untouched+def _offload_backend(+ monkeypatch,+ loader,+ device_map_kwargs = None,+):+ mod = _export_mod(monkeypatch)+ monkeypatch.setattr(mod, "FastLanguageModel", loader)+ monkeypatch.setattr(mod, "detect_audio_type", lambda *a, **k: None)+ monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_offline_window_if", lambda flag: contextlib.nullcontext())+ monkeypatch.setattr(mod, "_multi_gpu_device_map_kwargs", lambda: device_map_kwargs or {})+ backend = mod.ExportBackend.__new__(mod.ExportBackend)+ backend.cleanup_memory = lambda: None+ return mod, backend+++def _unsloth_spill_error():+ try:+ raise ValueError(+ "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM."+ )+ except ValueError as original:+ try:+ raise ValueError(+ "Unsloth: unsloth/gemma-4-E2B-it-unsloth-bnb-4bit does not fit in GPU memory "+ "(cuda:0 has 6.84 GB free), so transformers placed part of it on the CPU, "+ "which bitsandbytes cannot quantize."+ ) from original+ except ValueError as rewritten:+ return rewritten+++class _SpillUnlessOffloaded:+ calls: list[dict] = []++ @classmethod+ def from_pretrained(cls, **kwargs):+ cls.calls.append(kwargs)+ if "offload_layers" not in kwargs:+ raise _unsloth_spill_error()+ return types.SimpleNamespace(), types.SimpleNamespace()+++def test_load_that_fits_passes_no_offload_layers(monkeypatch, tmp_path):+ kwargs = _load_text_checkpoint(monkeypatch, tmp_path, {})+ assert "offload_layers" not in kwargs+ assert "device_map_planner_kwargs" not in kwargs+++def test_is_cpu_spill_rejection_sees_through_unsloths_rewrite(monkeypatch):+ mod = _export_mod(monkeypatch)+ assert mod._is_cpu_spill_rejection(_unsloth_spill_error())+ assert not mod._is_cpu_spill_rejection(ValueError("does not fit"))+++def test_single_gpu_spill_retries_with_auto_offload(monkeypatch, tmp_path):+ """#13696: the 4-bit export load spills to the CPU on an 8 GB card; retry streaming layers from host RAM."""+ _SpillUnlessOffloaded.calls = []+ mod, backend = _offload_backend(monkeypatch, _SpillUnlessOffloaded)+ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ ok, message = backend.load_checkpoint(str(checkpoint))+ assert ok, message+ calls = _SpillUnlessOffloaded.calls+ assert len(calls) == 2+ assert "offload_layers" not in calls[0]+ assert calls[1]["offload_layers"] == "auto"+ assert "device_map" not in calls[1]+ assert calls[1]["device_map_planner_kwargs"]["reserve_bytes"] == 1 << 30+++def test_offload_retry_runs_once(monkeypatch, tmp_path):+ class _AlwaysSpills:+ calls: list[dict] = []++ @classmethod+ def from_pretrained(cls, **kwargs):+ cls.calls.append(kwargs)+ raise _unsloth_spill_error()++ mod, backend = _offload_backend(monkeypatch, _AlwaysSpills)+ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ ok, message = backend.load_checkpoint(str(checkpoint))+ assert not ok+ assert "does not fit in GPU memory" in message+ assert len(_AlwaysSpills.calls) == 2+++def test_offload_layers_zero_disables_the_retry(monkeypatch, tmp_path):+ _SpillUnlessOffloaded.calls = []+ mod, backend = _offload_backend(monkeypatch, _SpillUnlessOffloaded)+ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ ok, message = backend.load_checkpoint(str(checkpoint), offload_layers = 0)+ assert not ok+ assert len(_SpillUnlessOffloaded.calls) == 1+++def test_load_checkpoint_forwards_explicit_offload_layers(monkeypatch, tmp_path):+ _RecordingLoader.calls = []+ mod, backend = _offload_backend(monkeypatch, _RecordingLoader)+ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ ok, message = backend.load_checkpoint(str(checkpoint), offload_layers = 8)+ assert ok, message+ assert _RecordingLoader.calls[0]["offload_layers"] == 8+++def test_load_checkpoint_omits_fixed_offload_on_balanced_map(monkeypatch, tmp_path):+ _RecordingLoader.calls = []+ mod, backend = _offload_backend(monkeypatch, _RecordingLoader, {"device_map": "balanced"})+ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ ok, message = backend.load_checkpoint(str(checkpoint), offload_layers = 8)+ assert ok, message+ assert "offload_layers" not in _RecordingLoader.calls[0]+ assert _RecordingLoader.calls[0]["device_map"] == "balanced"++def test_whisper_checkpoint_loads_with_its_processor_like_training(monkeypatch, tmp_path):mod = _export_mod(monkeypatch)_RecordingLoader.calls = []diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.tsindex c11e190885b..3c2ce2eeb0e 100644--- a/studio/frontend/src/features/export/api/export-api.ts+++ b/studio/frontend/src/features/export/api/export-api.ts@@ -172,6 +172,8 @@ export async function loadCheckpoint(params: {checkpoint_path: string;max_seq_length?: number;load_in_4bit?: boolean;+ /** Decoder layers in host RAM for low-VRAM export; "auto" (default) or a fixed count. */+ offload_layers?: number | "auto";/** Allow loading models with custom code. Only enable for checkpoints you trust. */trust_remote_code?: boolean;/** sha256 fingerprint pinning user approval of this exact custom-code version. */