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: probe the GPU once per embedding backend, not on every encode (#11142)
Wayne Sletcherdd25fe1f9800
diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.pyindex 7bcd79e6763..cd3c86b81cc 100644--- a/studio/backend/core/rag/embeddings.py+++ b/studio/backend/core/rag/embeddings.py@@ -662,6 +662,29 @@ def _resolve_auto() -> str:return "sentence-transformers"+# _resolve_auto's answer, kept with the backend it built: every encode, token count and identity+# check resolves auto, and its GPU probe is a subprocess (#10390).+_resident_hardware: tuple[object, str] | None = None+_hardware_probe = threading.local()+++def _resident_hardware_choice() -> str:+ """_resolve_auto, asked once for the backend that is published."""+ held = _resident_hardware+ if held is not None and _backend is not None and held[0] is _backend:+ return held[1]+ _hardware_probe.choice = _resolve_auto()+ return _hardware_probe.choice+++def _keep_hardware_choice(backend) -> None:+ """Keep the answer only when THIS call resolved it; see the clear in _get_backend."""+ global _resident_hardware+ choice = getattr(_hardware_probe, "choice", None)+ if choice is not None:+ _resident_hardware = (backend, choice)++def _model_is_local_gguf(model: str | None) -> bool:"""Whether ``model`` names a local .gguf file, or a folder holding one.@@ -728,7 +751,7 @@ def _resolve_auto_for_model(model_name: str | None = None) -> str:# safetensors has a validated ST plan.if _model_names_gguf_repo(model):return "llama-server"- return _resolve_auto()+ return _resident_hardware_choice()def sentence_transformers_runtime_available() -> bool:@@ -920,8 +943,12 @@ def _get_backend(model_name: str | None = None):with _backend_lock:model = model_name or config.effective_embedding_model()forced = _forced_backends.get(model)+ # Load-bearing: the identity and active-backend probes also resolve auto outside this lock,+ # so without the clear a build that short-circuited the hardware keeps their stale answer.+ _hardware_probe.choice = Nonekey = forced or (_resolve_auto_for_model(model) if raw in _AUTO_ALIASES else raw)if _backend is not None and _backend_key == _backend_cache_key(raw, key):+ _keep_hardware_choice(_backend)return _backendold = _backendif key in _ST_ALIASES:@@ -936,6 +963,7 @@ def _get_backend(model_name: str | None = None):"'auto', 'sentence-transformers' or 'llama-server'")_backend = new+ _keep_hardware_choice(new)if key in _ST_ALIASES and _is_llama_backend(new):# Pin the backend the warm probe actually fell back to, but let a different model retry ST.key = "llama-server"@@ -948,11 +976,12 @@ def _get_backend(model_name: str | None = None):def _reset_backend() -> None:"""Drop the cached backend (test teardown / re-init)."""- global _backend, _backend_key+ global _backend, _backend_key, _resident_hardwarewith _backend_lock:_forced_backends.clear()_backend = None_backend_key = None+ _resident_hardware = Nonedef backend_is_loaded(model_name: str | None = None) -> bool:@@ -998,12 +1027,13 @@ def release_backend() -> bool:Safe mid-ingestion: the next embed rebuilds, and the llama backend's own POSTretry already covers a server that went away under it."""- global _backend, _backend_key+ global _backend, _backend_key, _resident_hardwarewith _backend_lock:# Unload is an explicit fresh start, so a past runtime fallback stops pinning the choice and the saved# model picks its backend again._forced_backends.clear()backend, _backend, _backend_key = _backend, None, None+ _resident_hardware = Noneif backend is None:# Nothing published, but the module-level model can still be there (see backend_is_loaded);# freeing it here is what keeps that leak from being permanent.diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 1dff3de3252..8c7828e4eb7 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -912,7 +912,7 @@ def stub_embeddings(monkeypatch):from core.rag import config, embeddings- # Pin the backend: "auto" reprobes the hardware (nvidia-smi) on every use.+ # Pin the backend: "auto" probes the hardware (nvidia-smi) for each backend it builds.monkeypatch.setattr(config, "EMBED_BACKEND", "sentence-transformers")dim = 32diff --git a/studio/backend/tests/test_rag_embeddings.py b/studio/backend/tests/test_rag_embeddings.pyindex 6966b105145..df784079983 100644--- a/studio/backend/tests/test_rag_embeddings.py+++ b/studio/backend/tests/test_rag_embeddings.py@@ -176,6 +176,108 @@ def test_first_encode_builds_the_selected_backend_once(monkeypatch):assert builds == ["backend"]+class _AutoBackend:+ def encode(self, texts, **_kwargs):+ return np.zeros((len(texts), 4), dtype = np.float32)++ def token_counter(self, **_kwargs):+ return lambda text: len(text.split())++ def dim(self, **_kwargs):+ return 4+++def _resolve_auto_for(monkeypatch, *, stored = None):+ import utils.embedding_model_settings as ems++ asked: list[str] = []+ monkeypatch.setattr(config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(ems, "get_stored_backend", lambda _model: stored and stored["backend"])+ monkeypatch.setattr(+ embeddings, "_resolve_auto", lambda: asked.append("probe") or "sentence-transformers"+ )+ monkeypatch.setattr(+ embeddings, "_build_st_backend_or_fallback", lambda model_name = None: _AutoBackend()+ )+ return asked+++def test_auto_asks_the_hardware_once_for_the_backend_it_built(monkeypatch):+ """Every encode, token count and identity check resolves ``auto``, and the GPU probe+ behind it starts a subprocess, so asking per call started ~3 per indexed document (#10390)."""+ asked = _resolve_auto_for(monkeypatch)++ embeddings.encode(["first"], model_name = "org/embedder")+ assert asked == ["probe"]+ for _ in range(3):+ embeddings.encode(["again"], model_name = "org/embedder")+ embeddings.token_counter("org/embedder")("some words")+ embeddings.dim("org/embedder")+ embeddings.embedding_identity("org/embedder")+ assert asked == ["probe"]++ # An unload is a fresh start, so the next backend asks again.+ embeddings.release_backend()+ embeddings.encode(["after unload"], model_name = "org/embedder")+ assert asked == ["probe", "probe"]+++def test_a_saved_backend_still_replaces_a_resident_auto_backend(monkeypatch):+ """``auto`` is resolved per model so that saving a backend rebuilds (#9739); keeping the+ hardware answer must not keep the backend it chose."""+ stored = {"backend": None}+ _resolve_auto_for(monkeypatch, stored = stored)+ _patch_llama_backend(monkeypatch, binary = "/fake/llama-server")++ assert isinstance(embeddings._get_backend("org/embedder"), _AutoBackend)+ stored["backend"] = "llama-server"+ assert isinstance(embeddings._get_backend("org/embedder"), _SentinelLlamaBackend)+++def test_a_replaced_backend_asks_the_hardware_again(monkeypatch):+ """The kept answer is tied to the object it was kept for, and that tie is what makes a+ rebuild re-ask. Without it the tuple answers for a backend that is no longer published,+ so a host whose hardware moved keeps being told what it had before the rebuild."""+ asked = _resolve_auto_for(monkeypatch)+ _patch_llama_backend(monkeypatch, binary = "/fake/llama-server")++ first = embeddings._get_backend("org/embedder")+ assert asked == ["probe"]++ # A GGUF repo name resolves without the hardware, so the rebuild caches nothing of its own.+ monkeypatch.setattr(embeddings, "_model_names_gguf_repo", lambda _model: True)+ second = embeddings._get_backend("org/embedder")+ assert second is not first+ assert asked == ["probe"]++ # Back to a plain model: the published backend is no longer the one the answer was kept+ # for, so auto must go and ask rather than answer from the replaced backend's probe.+ monkeypatch.setattr(embeddings, "_model_names_gguf_repo", lambda _model: False)+ assert embeddings._resolve_auto_for_model("org/embedder") == "sentence-transformers"+ assert asked == ["probe", "probe"]+++def test_a_resolution_that_never_asked_the_hardware_keeps_nothing(monkeypatch):+ """``_get_backend`` clears the per-thread answer before resolving, and that clear is+ load-bearing: the identity and active-backend probes also resolve ``auto`` outside the+ lock, so without it a build that short-circuited the hardware would publish the answer+ an earlier, unrelated call had left behind."""+ asked = _resolve_auto_for(monkeypatch)+ _patch_llama_backend(monkeypatch, binary = "/fake/llama-server")++ # An out-of-lock caller resolves auto first, with no backend published yet.+ embeddings.active_backend_is_llama("org/embedder")+ assert asked == ["probe"]++ # Now build for a model that never reaches the hardware question.+ monkeypatch.setattr(embeddings, "_model_names_gguf_repo", lambda _model: True)+ built = embeddings._get_backend("org/embedder")+ assert isinstance(built, _SentinelLlamaBackend)++ # Nothing was kept, because this build asked the hardware nothing.+ assert embeddings._resident_hardware is None++def test_encode_is_serialized(monkeypatch):probe = _ConcurrencyProbe()monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _FakeModel(probe))