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: let another account join the resident GGUF instead of replacing it (#13038)

Daniel Han2e80b73a9859
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 558c4aa92aa..cbce05ca0c2 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -32663,6 +32663,33 @@ class LlamaCppBackend:
return False
return (self._hf_variant or "").lower() == (intent.hf_variant or "").lower()
+ def components_match_intent(self, intent: GgufLoadIntent) -> bool:
+ """``_runtime_matches_intent`` minus capacity and placement: same weights and components."""
+ if intent.force_reload or not self.matches_load_source(intent):
+ return False
+ requested = self.requested_extra_args
+ # Inherited extras would carry the resident's adapters and drafters unnamed by the caller.
+ if intent.extra_args_inherited and requested:
+ return False
+ extras = requested if intent.extra_args_inherited else intent.extra_args
+ if tuple(extras or ()) != tuple(requested or ()):
+ return False
+ if (self._chat_template_override or None) != (intent.chat_template_override or None):
+ return False
+ if not self._is_diffusion and (
+ bool(self._disable_vision) != bool(intent.disable_vision)
+ or self._requested_reasoning_budget
+ != resolve_reasoning_budget(extras, intent.reasoning_budget)
+ or self._requested_reasoning_budget_message
+ != resolve_reasoning_budget_message(extras, intent.reasoning_budget_message)
+ ):
+ return False
+ if _extra_args_set_spec_type(extras):
+ return self._requested_spec_mode is None
+ return (_canonicalize_spec_mode(intent.speculative_type) or "auto") == (
+ self._requested_spec_mode or "auto"
+ )
+
def _classify_gpu_offload(
self, expected_gpu: bool, detected_gpus: list[tuple[int, int]]
) -> Optional[bool]:
diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.py
index 19b51ec284f..4c569393efd 100644
--- a/studio/backend/hub/services/models/account_access.py
+++ b/studio/backend/hub/services/models/account_access.py
@@ -268,10 +268,24 @@ def join_resident(modality: str) -> None:
if not policy.installation_has_managed_accounts():
return
require_live_account()
+ # Seed the loader only with no record (pre-accounts); an empty one means it was retired.
+ loader = _resident_loader(modality)
with _sharers_lock:
+ if modality not in _resident_sharers and loader is not None:
+ _resident_sharers[modality] = {loader}
_resident_sharers.setdefault(modality, set()).add(current_account_id())
+def _resident_loader(modality: str) -> str | None:
+ """The publish record (zero-VRAM residents drop the GPU claim), else the GPU claim."""
+ recorded = _resident_accounts.get(modality)
+ if recorded is not None:
+ return recorded[0]
+ from core.inference import gpu_arbiter
+
+ return gpu_arbiter.owner_account() if gpu_arbiter.current_owner() == modality else None
+
+
def release_shared_resident(modality: str) -> bool:
"""Drop the caller's share while others keep the model; False leaves the share for a real unload."""
if not policy.installation_has_managed_accounts():
@@ -368,6 +382,15 @@ def resident_hidden(modality: str | None = None, reference: str | None = None) -
return False
+def joins_resident_runtime(modality: str, reference: str | None = None) -> bool:
+ """A managed caller that did not load the resident: an ordinary load joins it (#12365)."""
+ if resident_hidden(modality, reference):
+ return True
+ if not managed_account() or not resident_shared_with(modality, current_account_id()):
+ return False
+ return _resident_loader(modality) != current_account_id()
+
+
def hidden_resident_response():
return JSONResponse(content = {"loaded": True, "yours": False})
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index c16d5cfe3de..d12568fbbde 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -18275,7 +18275,17 @@ async def _load_model_impl(
== tuple(request._gguf_companion_roots)
and getattr(llama_backend, "_openai_gguf_companion_state", ())
== gguf_companion_state
- and llama_backend.adopt_load_intent_if_matched(intent)
+ and (
+ llama_backend.adopt_load_intent_if_matched(intent)
+ # Another account's capacity mismatch is its defaults, not a reconfig (#12365).
+ or (
+ replacing
+ and account_access.joins_resident_runtime(
+ "chat", llama_backend.model_identifier
+ )
+ and llama_backend.components_match_intent(intent)
+ )
+ )
and getattr(llama_backend, "_audio_probed", True)
):
return None
diff --git a/studio/backend/tests/multi_account/test_chat_resident_join_runtime.py b/studio/backend/tests/multi_account/test_chat_resident_join_runtime.py
new file mode 100644
index 00000000000..06cd2377b00
--- /dev/null
+++ b/studio/backend/tests/multi_account/test_chat_resident_join_runtime.py
@@ -0,0 +1,222 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""#12365: another account's ordinary load joins the resident GGUF despite other settings."""
+
+import asyncio
+import threading
+from types import SimpleNamespace
+
+import pytest
+from core.inference import gpu_arbiter
+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend
+from hub.services.models import account_access as access
+from models.inference import LoadRequest
+from routes import inference
+from state import active_generations
+from studio.backend.tests.multi_account.test_chat_shared_resident import ( # noqa: F401
+ RESIDENT,
+ VARIANT,
+ FakeLlama,
+ client_for,
+ shared,
+ sees_resident,
+)
+from utils.account_context import run_as
+
+
+class ReachedReplacement(Exception):
+ """The load left the reuse path for config resolution, the first step of a fresh load."""
+
+
+class StrictLlama(FakeLlama):
+ """Bob's resident: 2 slots, tensor parallel; the join uses the real component comparison."""
+
+ tensor_parallel = True
+ extra_args = None
+ hf_repo = RESIDENT
+ gguf_path = None
+ layer_preserves_tensor_intent = False
+ _is_diffusion = False
+ _chat_template_override = None
+ _requested_spec_mode = None
+ components_match_intent = LlamaCppBackend.components_match_intent
+
+ def __init__(self):
+ super().__init__()
+ self.last_load_intent = GgufLoadIntent(
+ model_identifier = RESIDENT,
+ hf_repo = RESIDENT,
+ hf_variant = VARIANT,
+ n_parallel = 2,
+ tensor_parallel = True,
+ )
+ self.adopted = []
+
+ def matches_load_source(self, intent):
+ return (
+ intent.model_identifier.lower() == RESIDENT.lower()
+ and (intent.hf_variant or "").lower() == VARIANT.lower()
+ )
+
+ def adopt_load_intent_if_matched(self, intent):
+ resident = self.last_load_intent
+ matched = self.matches_load_source(intent) and (
+ intent.n_parallel,
+ intent.tensor_parallel,
+ ) == (resident.n_parallel, resident.tensor_parallel)
+ if matched:
+ self.adopted.append(intent)
+ return matched
+
+
+def strict(monkeypatch, shared):
+ llama = StrictLlama()
+ monkeypatch.setattr(inference, "get_llama_cpp_backend", lambda: llama)
+ monkeypatch.setattr(
+ inference,
+ "_resolve_model_identifier_for_request",
+ lambda *a, **k: (RESIDENT, RESIDENT, False),
+ )
+ monkeypatch.setattr(inference, "resolve_effective_chat_template_override", lambda *a, **k: None)
+ monkeypatch.setattr(access, "require_model_access", lambda *a, **k: None)
+
+ def replacement(*a, **k):
+ raise ReachedReplacement()
+
+ monkeypatch.setattr(inference.ModelConfig, "from_identifier", replacement)
+ return llama
+
+
+def load(
+ account,
+ *,
+ force_reload = False,
+ gguf_variant = VARIANT,
+ **runtime,
+):
+ fastapi_request = SimpleNamespace(
+ app = SimpleNamespace(state = SimpleNamespace(llama_parallel_slots = 1))
+ )
+ request = LoadRequest(
+ model_path = RESIDENT, gguf_variant = gguf_variant, force_reload = force_reload, **runtime
+ )
+ try:
+ return run_as(
+ account,
+ lambda: asyncio.run(
+ inference._load_model_impl(
+ request, fastapi_request, current_subject = account.username
+ )
+ ),
+ )
+ except Exception as exc:
+ # The route wraps load failures in a 500; surface the sentinel it carries.
+ cause = exc
+ while cause is not None and not isinstance(cause, ReachedReplacement):
+ cause = cause.__cause__ or cause.__context__
+ if cause is not None:
+ raise cause from None
+ raise
+
+
+def test_matching_runtime_joins(strict, accounts):
+ response = load(accounts["alice"], n_parallel = 2, tensor_parallel = True)
+ assert response.status == "already_loaded"
+ assert accounts["alice"].account_id in access._resident_sharers["chat"]
+
+
[email protected]("busy", [False, True], ids = ["loader_idle", "loader_generating"])
+def test_other_account_default_runtime_joins_instead_of_replacing(strict, accounts, busy):
+ assert not sees_resident(accounts["alice"])
+ if busy:
+ with run_as(accounts["bob"], active_generations.ActiveGeneration, threading.Event()):
+ response = load(accounts["alice"])
+ else:
+ response = load(accounts["alice"])
+ assert response.status == "already_loaded"
+ assert not strict.unloaded
+ assert strict.adopted == []
+ assert strict.last_load_intent.n_parallel == 2 and strict.last_load_intent.tensor_parallel
+ assert access._resident_sharers["chat"] == {
+ accounts["alice"].account_id,
+ accounts["bob"].account_id,
+ }
+ assert sees_resident(accounts["alice"]) and sees_resident(accounts["bob"])
+
+
+def test_explicit_reload_from_another_account_is_still_a_replacement(strict, accounts):
+ with pytest.raises(ReachedReplacement):
+ load(accounts["alice"], force_reload = True)
+ assert accounts["alice"].account_id not in access._resident_sharers["chat"]
+
+
+def test_different_variant_from_another_account_is_still_a_replacement(strict, accounts):
+ with pytest.raises(ReachedReplacement):
+ load(accounts["alice"], gguf_variant = "Q8_0")
+ assert accounts["alice"].account_id not in access._resident_sharers["chat"]
+
+
+def test_the_loader_changing_its_own_runtime_is_still_a_replacement(strict, accounts):
+ with pytest.raises(ReachedReplacement):
+ load(accounts["bob"], n_parallel = 4)
+
+
+def test_a_custom_template_on_the_resident_is_not_joined_by_default(strict, accounts):
+ strict._chat_template_override = "{{ bob's template }}"
+ with pytest.raises(ReachedReplacement):
+ load(accounts["alice"])
+ assert accounts["alice"].account_id not in access._resident_sharers["chat"]
+
+
+def test_resident_extras_are_not_joined_by_an_account_that_did_not_send_them(strict, accounts):
+ strict.requested_extra_args = ["--lora", "/bob/workspace/adapter.gguf"]
+ with pytest.raises(ReachedReplacement):
+ load(accounts["alice"], llama_extra_args = [])
+ assert accounts["alice"].account_id not in access._resident_sharers["chat"]
+
+
+def test_joining_a_resident_with_no_sharer_record_keeps_its_loader(monkeypatch, strict, accounts):
+ monkeypatch.setattr(access, "_resident_sharers", {})
+ assert load(accounts["alice"]).status == "already_loaded"
+ assert access._resident_sharers["chat"] == {
+ accounts["alice"].account_id,
+ gpu_arbiter.owner_account(),
+ }
+ with client_for(accounts["alice"]) as client:
+ left = client.post("/api/inference/unload", json = {"model_path": RESIDENT})
+ assert left.status_code == 200, left.text
+ assert not strict.unloaded
+
+
+def test_the_installation_owner_sees_the_resident_so_its_mismatch_still_replaces(strict, accounts):
+ with pytest.raises(ReachedReplacement):
+ load(accounts["unsloth"])
+
+
+def test_repeating_the_load_that_joined_joins_again(strict, accounts):
+ assert load(accounts["alice"]).status == "already_loaded"
+ assert load(accounts["alice"]).status == "already_loaded"
+ assert not strict.unloaded and strict.adopted == []
+
+
+def test_inherited_extras_do_not_join_a_resident_with_extras(strict, accounts):
+ strict.requested_extra_args = ["--lora", "/bob/workspace/adapter.gguf"]
+ strict.extra_args = list(strict.requested_extra_args)
+ with pytest.raises(ReachedReplacement):
+ load(accounts["alice"])
+ assert accounts["alice"].account_id not in access._resident_sharers["chat"]
+
+
+def test_a_zero_vram_loader_changing_its_own_runtime_still_replaces(monkeypatch, strict, accounts):
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)
+ with pytest.raises(ReachedReplacement):
+ load(accounts["bob"], n_parallel = 4)
+
+
+def test_a_retired_loader_is_not_seeded_back(strict, accounts):
+ access.retire_resident_shares(accounts["bob"].account_id)
+ assert load(accounts["alice"]).status == "already_loaded"
+ assert access._resident_sharers["chat"] == {accounts["alice"].account_id}