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: chat with a fine-tuned model by the name its job returns (#15449)

Nilayc4f9de9c0580
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 398af25de12..40e3b8f5bfc 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -9909,6 +9909,10 @@ def _loaded_satisfies(requested: str) -> bool:
matches = _matches_any(
base, [active, public_model_id(active), getattr(backend, "_openai_advertised_id", None)]
)
+ if not matches:
+ # a fine-tuning job's "<run>/checkpoint-N" name for the folder loaded by path
+ trained = _trained_run_dir(requested)
+ matches = trained is not None and _norm_path(trained) == _norm_path(active)
if not matches:
return False
# Only llama.cpp carries a quant identity, so this backend can only match on the repo.
@@ -10003,6 +10007,39 @@ def _matches_any(requested: str, candidates) -> bool:
return False
+_TRAINED_CHECKPOINT = re.compile(r"checkpoint-\d+")
+
+
+def _trained_run_dir(model: Optional[str]) -> Optional[str]:
+ """The outputs folder a fine-tuning job names as ``<run>`` or ``<run>/checkpoint-<step>``."""
+ from utils.paths import outputs_root
+
+ if not isinstance(model, str) or "\\" in model:
+ return None
+ parts = model.split("/")
+ if len(parts) > 2 or (len(parts) == 2 and not _TRAINED_CHECKPOINT.fullmatch(parts[1])):
+ return None
+ if any(part in ("", ".", "..") or part != os.path.basename(part) for part in parts):
+ return None
+ try:
+ run_dir = outputs_root().joinpath(*parts)
+ return str(run_dir) if run_dir.is_dir() else None
+ except (OSError, ValueError):
+ return None
+
+
+def _resolve_trained_run_request(request) -> bool:
+ """Rewrites a run or checkpoint name on a load / unload request to its folder."""
+ trained = _trained_run_dir(request.model_path)
+ if not trained:
+ return False
+ from hub.utils.host_paths import note_resolved_handle
+
+ note_resolved_handle(request.model_path, trained)
+ request.model_path = trained
+ return True
+
+
def _looks_like_local_path(value: str) -> bool:
"""A filesystem path rather than a repo id, so case matters."""
text = str(value)
@@ -10223,7 +10260,7 @@ async def _reject_unservable_model(
),
)
- still_indexing = torn = False
+ still_indexing = torn = trained = False
try:
if await asyncio.to_thread(_loaded_satisfies, requested_model):
return
@@ -10308,7 +10345,10 @@ async def _reject_unservable_model(
and base.strip().count("/") == 1
and await asyncio.to_thread(local_gguf_torn_only, base)
)
- here = here or torn
+ trained = (
+ not here and await asyncio.to_thread(_trained_run_dir, requested_model) is not None
+ )
+ here = here or torn or trained
switchable = downloaded and get_openai_auto_switch_enabled()
except HTTPException:
# A refusal decided above must propagate, not fall through to the resident model.
@@ -10318,7 +10358,7 @@ async def _reject_unservable_model(
logger.debug("unservable-model check failed for %r: %s", requested_model, exc)
if not quantified:
return
- downloaded = here = switchable = torn = False
+ downloaded = here = switchable = torn = trained = False
if still_indexing:
_raise_still_indexing(requested_model, fastapi_request)
if gguf_hub_repo and not (quantified or here):
@@ -10351,6 +10391,12 @@ async def _reject_unservable_model(
f"The model '{requested_model}' is only partly downloaded on this server, so it "
"cannot be served. Finish the download in Unsloth Studio."
)
+ elif trained:
+ status_code, code = 404, "model_not_found"
+ message = (
+ f"The fine-tuned model '{requested_model}' is not loaded. Load it in Unsloth "
+ "Studio, or with POST /api/inference/load, then retry."
+ )
elif downloaded:
status_code, code = 404, "model_not_found"
message = (
@@ -10382,6 +10428,11 @@ async def _require_named_model_access(
named_model: str, fastapi_request: Optional[Request] = None
) -> None:
"""Authorize a named model via the account catalog, or an uncached Hub ref via caller token."""
+ trained = await asyncio.to_thread(_trained_run_dir, named_model)
+ if trained is not None:
+ # a run name is no Hub id: the Hub allowlist would refuse it, so authorize the folder
+ await asyncio.to_thread(account_access.require_model_access, trained)
+ return
try:
await asyncio.to_thread(account_access.require_model_access, named_model)
return
@@ -10885,8 +10936,13 @@ async def _maybe_auto_switch_model(
include_companion_scope = True,
)
if resolved is None:
+ # A "<run>/checkpoint-N" name looks like a Hub id; the reject below refuses it instead.
+ trained = (
+ not reload_only
+ and await asyncio.to_thread(_trained_run_dir, requested_model) is not None
+ )
# Not on disk. Opt-in: fetch in the background and ask the caller to retry.
- if auto_switch_on and not reload_only:
+ if auto_switch_on and not reload_only and not trained:
await _maybe_auto_download_model(
requested_model,
fastapi_request,
@@ -17037,6 +17093,10 @@ async def load_model(
GGUF models load via llama-server (llama.cpp) instead of Unsloth.
"""
+ named = request.model_path
+ if _resolve_trained_run_request(request):
+ # keeps the job's name as the served id, so chat and /v1/models answer to it
+ request._advertised_id = request._advertised_id or named
return await _tunnel_safe_json(
load_model_gated(request, fastapi_request, current_subject, user_initiated = True),
label = "Model load",
@@ -20689,6 +20749,8 @@ async def unload_model(request: UnloadRequest, current_subject: str = Depends(ge
``_unload_model_impl`` (as preview awaits ``load_model_gated``), since the padded
path returns a StreamingResponse, not the payload.
"""
+ # /load records a run name as its folder, so unload and cancel by the same spelling
+ _resolve_trained_run_request(request)
return await _tunnel_safe_json(
_unload_model_impl(request, current_subject), label = "Model unload"
)
diff --git a/studio/backend/tests/test_fine_tuned_model_serving.py b/studio/backend/tests/test_fine_tuned_model_serving.py
new file mode 100644
index 00000000000..fc77974d62f
--- /dev/null
+++ b/studio/backend/tests/test_fine_tuned_model_serving.py
@@ -0,0 +1,228 @@
+# 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 asyncio
+from contextlib import asynccontextmanager
+
+import pytest
+from fastapi import HTTPException
+
+import routes.inference as inference_route
+from core.inference import llama_keepwarm
+from utils.paths import outputs_root
+
+BASE = "unsloth/SmolLM2-135M-Instruct"
+RUN = "unsloth_SmolLM2-135M-Instruct_1792969744"
+
+
+class _Url:
+ path = "/v1/chat/completions"
+
+
+class _Req:
+ url = _Url()
+ headers = {}
+
+
+def _run_dir():
+ run_dir = outputs_root() / RUN
+ run_dir.mkdir(parents = True)
+ (run_dir / "adapter_config.json").write_text("{}")
+ return run_dir
+
+
+def _wire(active, monkeypatch):
+ idle = type("B", (), {"is_loaded": False, "model_identifier": None, "hf_variant": None})()
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: idle)
+ monkeypatch.setattr(
+ inference_route,
+ "get_inference_backend",
+ lambda: type("B", (), {"active_model_name": active})(),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.index_is_built", lambda: True)
+ monkeypatch.setattr("core.inference.local_model_resolver.warm_index_soon", lambda: None)
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.resolve_local_gguf", lambda _n, **_kw: None
+ )
+
+ async def _unavailable(model):
+ return f"The model '{model}' is not downloaded on this server."
+
+ monkeypatch.setattr(inference_route, "_unavailable_model_message", _unavailable)
+
+
+def _reject(model, active, monkeypatch):
+ _wire(active, monkeypatch)
+ return asyncio.run(inference_route._reject_unservable_model(model, _Req()))
+
+
+def test_a_fine_tuned_model_is_not_answered_by_the_resident_base_model(monkeypatch):
+ _run_dir()
+ with pytest.raises(HTTPException) as excinfo:
+ _reject(RUN, BASE, monkeypatch)
+ assert excinfo.value.status_code == 404
+ assert RUN in excinfo.value.detail["error"]["message"]
+
+
+def test_a_loaded_fine_tuned_model_answers_under_its_name(monkeypatch):
+ run_dir = _run_dir()
+ assert _reject(RUN, str(run_dir), monkeypatch) is None
+
+
+def test_an_unknown_bare_name_still_uses_the_resident_model(monkeypatch):
+ _run_dir()
+ assert _reject("some-label", BASE, monkeypatch) is None
+
+
+def test_loading_a_fine_tuned_model_by_name_loads_its_run_folder(monkeypatch):
+ run_dir = _run_dir()
+
+ @asynccontextmanager
+ async def _gate():
+ yield
+
+ loaded = []
+
+ async def _impl(request, *_args, **_kwargs):
+ loaded.append((request.model_path, request._advertised_id))
+ return {"status": "loaded", "model": request.model_path}
+
+ monkeypatch.setattr(inference_route, "_raise_if_sidecar_swap_in_progress", lambda: None)
+ monkeypatch.setattr(inference_route, "_pending_load_attempts", {})
+ monkeypatch.setattr(llama_keepwarm, "inference_lifecycle_gate", _gate)
+ monkeypatch.setattr(inference_route, "_run_tracked_load_model_impl", _impl)
+
+ answers = [
+ asyncio.run(
+ inference_route.load_model(
+ inference_route.LoadRequest(model_path = model_path), object(), "test"
+ )
+ )
+ for model_path in (RUN, BASE)
+ ]
+
+ assert loaded == [(str(run_dir), RUN), (BASE, None)]
+ assert [answer["model"] for answer in answers] == [RUN, BASE]
+
+
+CHECKPOINT = f"{RUN}/checkpoint-5"
+
+
+def test_a_checkpoint_name_is_refused_until_that_checkpoint_is_loaded(monkeypatch):
+ checkpoint_dir = _run_dir() / "checkpoint-5"
+ checkpoint_dir.mkdir()
+ with pytest.raises(HTTPException) as excinfo:
+ _reject(CHECKPOINT, BASE, monkeypatch)
+ assert excinfo.value.status_code == 404
+ assert CHECKPOINT in excinfo.value.detail["error"]["message"]
+ assert _reject(CHECKPOINT, str(checkpoint_dir), monkeypatch) is None
+
+
+ "name",
+ ["..", ".", "", f"{RUN}/..", f"{RUN}/other", f"../{RUN}", f"{RUN}\\checkpoint-5", "a/b/c"],
+)
+def test_only_run_and_checkpoint_names_map_into_outputs(name):
+ run_dir = _run_dir()
+ (run_dir / "other").mkdir()
+ assert inference_route._trained_run_dir(name) is None
+ assert inference_route._trained_run_dir(RUN) == str(run_dir)
+
+
+async def _never_held_back(_request):
+ return False
+
+
+def test_switch_by_request_never_fetches_a_checkpoint_name_from_the_hub(monkeypatch):
+ from utils import openai_auto_switch_settings as settings
+ from core.inference import local_model_resolver as resolver
+
+ checkpoint_dir = _run_dir() / "checkpoint-5"
+ checkpoint_dir.mkdir()
+ downloads = []
+
+ async def _download(model, *_args, **_kwargs):
+ downloads.append(model)
+
+ monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: True)
+ monkeypatch.setattr(resolver, "resolve_local_gguf_for_switch", lambda *_a, **_kw: None)
+ monkeypatch.setattr(resolver, "resolve_trusted_cached_local_gguf", lambda *_a, **_kw: None)
+ monkeypatch.setattr(inference_route, "_audio_cpp_switch_target", lambda _m: None)
+ monkeypatch.setattr(inference_route, "_maybe_auto_download_model", _download)
+ monkeypatch.setattr(inference_route, "_keyless_caller_held_back", _never_held_back)
+
+ def _switch(active):
+ _wire(active, monkeypatch)
+ return asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ CHECKPOINT, _Req(), "test", claim_resident = False
+ )
+ )
+
+ with pytest.raises(HTTPException) as excinfo:
+ _switch(BASE)
+ assert excinfo.value.status_code == 404
+ assert _switch(str(checkpoint_dir)) is None
+ assert downloads == []
+
+
+def test_a_managed_account_may_name_its_own_run(monkeypatch):
+ run_dir = _run_dir()
+ checked = []
+
+ def _require(model):
+ # an allowlist such as unsloth/* refuses a bare run name as a Hub id
+ checked.append(model)
+ if model != str(run_dir):
+ raise HTTPException(status_code = 403, detail = "Model not allowed")
+
+ monkeypatch.setattr(inference_route.account_access, "require_model_access", _require)
+
+ asyncio.run(inference_route._require_named_model_access(RUN))
+ assert checked == [str(run_dir)]
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route._require_named_model_access("someone-elses-run"))
+ assert excinfo.value.status_code == 403
+
+
+def test_unloading_by_checkpoint_name_targets_the_folder_it_loads(monkeypatch):
+ from models.inference import UnloadRequest, UnloadResponse
+
+ checkpoint_dir = _run_dir() / "checkpoint-5"
+ checkpoint_dir.mkdir()
+ seen = []
+
+ async def _impl(request, _subject):
+ seen.append((request.model_path, request.cancel_load_request_id))
+ return UnloadResponse(status = "unloaded", model = request.model_path)
+
+ monkeypatch.setattr(inference_route, "_unload_model_impl", _impl)
+ answers = [
+ asyncio.run(
+ inference_route.unload_model(
+ UnloadRequest(model_path = CHECKPOINT, cancel_load_request_id = request_id), "test"
+ )
+ )
+ for request_id in (None, "attempt-1")
+ ]
+
+ assert seen == [(str(checkpoint_dir), None), (str(checkpoint_dir), "attempt-1")]
+ assert [answer["model"] for answer in answers] == [CHECKPOINT, CHECKPOINT]
+
+
+def test_a_checkpoint_loaded_by_path_answers_to_its_job_name(monkeypatch):
+ # what the extra-slot router asks each slot, so a checkpoint kept alongside is found too
+ checkpoint_dir = _run_dir() / "checkpoint-5"
+ checkpoint_dir.mkdir()
+ _wire(str(checkpoint_dir), monkeypatch)
+ assert inference_route._loaded_satisfies(CHECKPOINT)
+ assert not inference_route._loaded_satisfies(f"{RUN}/checkpoint-6")
+ _wire(str(outputs_root() / RUN), monkeypatch)
+ assert not inference_route._loaded_satisfies(CHECKPOINT)
+
+
+def test_a_checkpoint_loaded_by_a_forward_slash_drive_path_is_recognized(monkeypatch):
+ windows_dir = "C:/Studio/outputs/run/checkpoint-5"
+ monkeypatch.setattr(inference_route, "_trained_run_dir", lambda _m: windows_dir)
+ _wire(windows_dir, monkeypatch)
+ assert inference_route._loaded_satisfies(CHECKPOINT)
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index e48e704a14f..4c1825eb1a1 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -10029,7 +10029,11 @@ class TestApiMonitorSafetensorsUsage:
):
if getattr(func, "__name__", "") == "resolve_local_gguf":
return None
- if func in (inf_mod.get_inference_backend, inf_mod._loaded_satisfies):
+ if func in (
+ inf_mod.get_inference_backend,
+ inf_mod._loaded_satisfies,
+ inf_mod._trained_run_dir,
+ ):
return func(*_args, **_kwargs)
raise asyncio.CancelledError()