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: add an embedding device setting for RAG (#13365)

Daniel Han1f20a5f59971
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.py
index 0732e99ef89..87dba7bf85d 100644
--- a/studio/backend/core/rag/config.py
+++ b/studio/backend/core/rag/config.py
@@ -276,7 +276,7 @@ EMBED_GGUF_VARIANT = os.environ.get("RAG_EMBED_GGUF_VARIANT", "F16")
EMBED_DEVICE = os.environ.get("RAG_EMBED_DEVICE", "auto")
-def embed_device_preference() -> str:
+def _env_embed_device() -> str:
"""``EMBED_DEVICE`` normalized to exactly ``gpu``, ``cpu`` or ``auto``.
One reader for both backends, because they used to disagree about the same
@@ -294,6 +294,23 @@ def embed_device_preference() -> str:
return "auto"
+def embed_device_locked() -> bool:
+ """Whether ``RAG_EMBED_DEVICE`` names a device, which Settings then cannot override."""
+ return _env_embed_device() != "auto"
+
+
+def embed_device_preference() -> str:
+ """``gpu``, ``cpu`` or ``auto``: ``RAG_EMBED_DEVICE`` when it names a device, else the Settings choice."""
+ env = _env_embed_device()
+ if env != "auto":
+ return env
+ try:
+ from utils.embedding_model_settings import get_stored_embedding_device
+ return get_stored_embedding_device()
+ except Exception: # noqa: BLE001 - store unavailable: each backend's default
+ return "auto"
+
+
def embed_device_requires_gpu() -> bool:
"""True when a failed GPU start must raise instead of retrying on CPU.
diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.py
index 9f3a975eb31..7fc872b96fd 100644
--- a/studio/backend/core/rag/embeddings.py
+++ b/studio/backend/core/rag/embeddings.py
@@ -64,7 +64,7 @@ def _device() -> str:
The trade is small at these sizes: one 128-token chunk takes 18.7ms on CPU against 5.2ms on
CUDA. Bulk indexing is where it shows (batch 64: 445 chunks/s on CPU against 3174/s), and
- ``RAG_EMBED_DEVICE=gpu`` opts back in for a large corpus.
+ Settings (GPU) or ``RAG_EMBED_DEVICE=gpu`` opts back in for a large corpus.
This reads the same setting as the llama-server backend but resolves ``auto`` differently, which
is intended: that backend offloads inside its own subprocess, where the context dies with the
@@ -611,7 +611,21 @@ def _get(model_name: str | None = None):
# Re-emit in finally: a load that raises after transformers wrote its report is exactly when a
# MISSING or MISMATCH line matters.
try:
- _model = SentenceTransformer(load_target, **st_kwargs)
+ try:
+ _model = SentenceTransformer(load_target, **st_kwargs)
+ except Exception as exc: # noqa: BLE001 - e.g. CUDA OOM beside a resident chat model
+ # Retry on CPU before encode()'s llama-server fallback, which changes the embedding space.
+ if device == "cpu" or config.embed_device_requires_gpu():
+ raise
+ logger.warning(
+ "loading embedding model %s on %s failed (%s); retrying on CPU",
+ name,
+ device,
+ exc,
+ )
+ st_kwargs["device"] = "cpu"
+ st_kwargs["model_kwargs"] = dtype_kwargs(_load_dtype("cpu", name))
+ _model = SentenceTransformer(load_target, **st_kwargs)
finally:
_emit_load_reports(report)
_name = name
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index f1f1147f28b..352300c730b 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -202,6 +202,7 @@ from utils.embedding_model_settings import (
get_rag_embedding_model,
get_stored_embedding_model,
reset_rag_embedding_model,
+ set_embedding_device,
set_rag_embedding_model,
validate_embedding_model,
)
@@ -2839,10 +2840,26 @@ class EmbeddingModelResponse(BaseModel):
loaded: bool = False
# Whether ANY embedder is resident.
backend_loaded: bool = False
+ embedding_device: Literal["auto", "cpu", "gpu"] = "auto"
+ # RAG_EMBED_DEVICE names a device, so Settings shows it read-only.
+ embedding_device_locked: bool = False
+
+
+class EmbeddingDevicePayload(BaseModel):
+ device: Literal["auto", "cpu", "gpu"]
+
+
+def _embedding_device_state() -> tuple[str, bool]:
+ from core.rag import config as rag_config
+ try:
+ return rag_config.embed_device_preference(), rag_config.embed_device_locked()
+ except Exception: # noqa: BLE001 - probe must never block reading settings
+ return "auto", False
def _embedding_model_response() -> EmbeddingModelResponse:
model = get_rag_embedding_model()
+ device, device_locked = _embedding_device_state()
return EmbeddingModelResponse(
embedding_model = model,
embedding_gguf_repo = effective_gguf_repo_for_embedding_model(model),
@@ -2851,6 +2868,8 @@ def _embedding_model_response() -> EmbeddingModelResponse:
is_custom = get_stored_embedding_model() is not None,
loaded = _embedder_is_loaded(model),
backend_loaded = _any_embedder_is_loaded(),
+ embedding_device = device,
+ embedding_device_locked = device_locked,
)
@@ -3817,6 +3836,29 @@ def unload_embedding_model(
return _embedding_model_response()
+@_owner_settings_router.put("/embedding-model/device", response_model = EmbeddingModelResponse)
+def update_embedding_device(
+ payload: EmbeddingDevicePayload, current_subject: str = Depends(get_current_subject)
+) -> EmbeddingModelResponse:
+ """Run the embedder on the CPU, the GPU, or the hardware default, for every embedding model. The vectors
+ keep their embedding space, so indexed documents stay searchable. A failed GPU start falls back to CPU."""
+ from core.rag import config as rag_config
+
+ if rag_config.embed_device_locked():
+ raise HTTPException(
+ status_code = 409, detail = "The embedding device is set by RAG_EMBED_DEVICE."
+ )
+ if set_embedding_device(payload.device):
+ from core.rag import embeddings
+
+ # The resident embedder stays on its old device until rebuilt; the next index or search rebuilds it.
+ embeddings.release_backend()
+ logger.info(
+ "settings.embedding_device_updated subject=%s device=%s", current_subject, payload.device
+ )
+ return _embedding_model_response()
+
+
@_owner_settings_router.delete("/embedding-model", response_model = EmbeddingModelResponse)
def reset_embedding_model(
current_subject: str = Depends(get_current_subject),
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 76f6a077d6e..222c1159a37 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -139,6 +139,19 @@ def _forget_mxc_isolation_settings():
_forget()
[email protected](autouse = True)
+def _forget_embedding_device_setting():
+ # Same one-store-per-test reason as above.
+ def _forget():
+ settings = sys.modules.get("utils.embedding_model_settings")
+ if settings is not None:
+ settings.forget_cached_embedding_device()
+
+ _forget()
+ yield
+ _forget()
+
+
@pytest.fixture(autouse = True)
def _no_background_sandbox_probes(monkeypatch):
# No warm-up thread and no background re-probe; each test starts with no cached tool answer.
diff --git a/studio/backend/tests/test_account_chat_settings.py b/studio/backend/tests/test_account_chat_settings.py
index 1a27497aa61..420332e347f 100644
--- a/studio/backend/tests/test_account_chat_settings.py
+++ b/studio/backend/tests/test_account_chat_settings.py
@@ -372,6 +372,7 @@ OWNER_PATHS = [
"/embedding-model": ("GET", "PUT", "DELETE"),
"/embedding-model/resolve": ("GET",),
"/embedding-model/unload": ("POST",),
+ "/embedding-model/device": ("PUT",),
"/preview-links/rotate": ("POST",),
"/remote-access": ("GET",),
"/remote-access/start": ("POST",),
diff --git a/studio/backend/tests/test_embedding_model_security_gate.py b/studio/backend/tests/test_embedding_model_security_gate.py
index f0e47113a90..87babb27726 100644
--- a/studio/backend/tests/test_embedding_model_security_gate.py
+++ b/studio/backend/tests/test_embedding_model_security_gate.py
@@ -461,6 +461,8 @@ def test_clean_repo_saves_under_force(client, monkeypatch):
"loaded": False,
# Nor is any other model, so the Unload control stays hidden too.
"backend_loaded": False,
+ "embedding_device": "auto",
+ "embedding_device_locked": False,
}
diff --git a/studio/backend/tests/test_rag_embedding_device_setting.py b/studio/backend/tests/test_rag_embedding_device_setting.py
new file mode 100644
index 00000000000..f4311be50d2
--- /dev/null
+++ b/studio/backend/tests/test_rag_embedding_device_setting.py
@@ -0,0 +1,178 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Settings > Documents & RAG > Embedding device: RAG_EMBED_DEVICE first, then the owner's saved choice."""
+
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from fastapi import HTTPException
+
+from core.rag import config, embeddings
+from core.rag.embed_llama_server import LlamaServerBackend
+from routes import settings as settings_routes
+from storage import studio_db
+from utils import embedding_model_settings as ems
+from utils.account_context import AccountContext, bind_account, reset_account
+from utils.hardware.hardware import DeviceType
+
+ALICE = AccountContext("a" * 32, "alice")
+
+
[email protected](autouse = True)
+def isolated_home(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(studio_db, "_schema_ready", set())
+ monkeypatch.setattr(config, "EMBED_DEVICE", "auto")
+ ems.forget_cached_embedding_device()
+ yield
+ ems.forget_cached_embedding_device()
+
+
+def released(monkeypatch):
+ calls = []
+ monkeypatch.setattr(embeddings, "release_backend", lambda: calls.append(1) or True)
+ return calls
+
+
+def _put(device):
+ return settings_routes.update_embedding_device(
+ settings_routes.EmbeddingDevicePayload(device = device), current_subject = "owner"
+ )
+
+
+def test_unset_keeps_each_backends_hardware_default():
+ assert config.embed_device_preference() == "auto"
+ assert config.embed_device_locked() is False
+
+
+def test_saved_gpu_moves_every_model_to_the_gpu(monkeypatch, released):
+ """Both backends read the one preference, so the choice is not tied to a model."""
+ monkeypatch.setattr(embeddings, "get_device", lambda: DeviceType.CUDA)
+ assert embeddings._device() == "cpu"
+
+ response = _put("gpu")
+
+ assert response.embedding_device == "gpu"
+ assert response.embedding_device_locked is False
+ assert released == [1]
+ assert embeddings._device() == "cuda"
+ assert LlamaServerBackend()._use_gpu() is True
+ # A Settings choice is a preference: a failed GPU start still falls back to CPU.
+ assert config.embed_device_requires_gpu() is False
+
+
+def test_saved_cpu_keeps_llama_server_off_the_gpu(monkeypatch, released):
+ monkeypatch.setattr(LlamaServerBackend, "_gpu_available", staticmethod(lambda: True))
+ assert LlamaServerBackend()._use_gpu() is True
+ _put("cpu")
+ assert LlamaServerBackend()._use_gpu() is False
+
+
+def test_saving_the_same_device_again_keeps_the_embedder_resident(released):
+ _put("gpu")
+ _put("gpu")
+ assert released == [1]
+ _put("auto")
+ assert released == [1, 1]
+ assert config.embed_device_preference() == "auto"
+
+
+def test_the_choice_is_installation_wide(released):
+ _put("gpu")
+ token = bind_account(ALICE)
+ try:
+ assert config.embed_device_preference() == "gpu"
+ finally:
+ reset_account(token)
+
+
[email protected]("env, expected", [("gpu", "gpu"), (" cuda ", "gpu"), ("cpu", "cpu")])
+def test_a_device_in_the_environment_wins_and_locks_settings(monkeypatch, released, env, expected):
+ ems.set_embedding_device("cpu" if expected == "gpu" else "gpu")
+ monkeypatch.setattr(config, "EMBED_DEVICE", env)
+
+ assert config.embed_device_preference() == expected
+ assert settings_routes._embedding_device_state() == (expected, True)
+ with pytest.raises(HTTPException) as exc:
+ _put("auto")
+ assert exc.value.status_code == 409
+ assert released == []
+
+
+def test_environment_auto_leaves_the_choice_to_settings(monkeypatch, released):
+ monkeypatch.setattr(config, "EMBED_DEVICE", "auto")
+ _put("gpu")
+ assert config.embed_device_preference() == "gpu"
+
+
+def test_an_unrecognized_stored_value_reads_as_auto():
+ studio_db.upsert_app_settings({ems.EMBEDDING_DEVICE_SETTING_KEY: "banana"})
+ assert ems.get_stored_embedding_device() == "auto"
+ with pytest.raises(ValueError):
+ ems.set_embedding_device("banana")
+
+
+def test_a_read_overlapping_a_save_does_not_cache_the_old_device(monkeypatch, released):
+ """A settings poll that read the old value before a PUT landed must not pin it in the cache."""
+ real_get = studio_db.get_app_setting
+
+ def slow_get(key, fallback = None):
+ value = real_get(key, fallback)
+ if key == ems.EMBEDDING_DEVICE_SETTING_KEY and value is None:
+ # The PUT commits between this reader's DB read and its cache fill.
+ monkeypatch.setattr(studio_db, "get_app_setting", real_get)
+ _put("gpu")
+ return value
+
+ monkeypatch.setattr(studio_db, "get_app_setting", slow_get)
+ # Frozen clock: the stale entry must still be inside its TTL when the next reader asks.
+ monkeypatch.setattr(ems, "time", SimpleNamespace(monotonic = lambda: 1000.0))
+ assert ems.get_stored_embedding_device() == "auto"
+ assert config.embed_device_preference() == "gpu"
+
+
[email protected]("env, retried", [("auto", True), ("gpu", False)])
+def test_a_failed_gpu_load_retries_on_cpu_unless_the_environment_insists(
+ monkeypatch, tmp_path, released, env, retried
+):
+ """Out of VRAM beside a chat model: Settings' GPU falls back to CPU in the same embedding space."""
+ attempts = []
+
+ class FakeSentenceTransformer:
+ def __init__(self, name, **kwargs):
+ attempts.append(kwargs["device"])
+ if kwargs["device"] != "cpu":
+ raise RuntimeError("CUDA out of memory")
+
+ monkeypatch.setitem(
+ sys.modules,
+ "sentence_transformers",
+ SimpleNamespace(SentenceTransformer = FakeSentenceTransformer),
+ )
+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)
+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)
+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cuda")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.active_hf_hub_cache", lambda: str(tmp_path / "hub")
+ )
+ monkeypatch.setattr(embeddings, "_model", None)
+ monkeypatch.setattr(embeddings, "_name", None)
+ _put("gpu")
+ monkeypatch.setattr(config, "EMBED_DEVICE", env)
+
+ if retried:
+ embeddings._get("Org/Embedder")
+ assert attempts == ["cuda", "cpu"]
+ else:
+ with pytest.raises(RuntimeError, match = "out of memory"):
+ embeddings._get("Org/Embedder")
+ assert attempts == ["cuda"]
diff --git a/studio/backend/utils/embedding_model_settings.py b/studio/backend/utils/embedding_model_settings.py
index 97c90bf1b31..f1a1bd9e83d 100644
--- a/studio/backend/utils/embedding_model_settings.py
+++ b/studio/backend/utils/embedding_model_settings.py
@@ -329,3 +329,61 @@ def reset_rag_embedding_model() -> str:
)
_invalidate_cache()
return restored
+
+
+EMBEDDING_DEVICE_SETTING_KEY = "rag_embedding_device"
+EMBEDDING_DEVICE_CHOICES = ("auto", "cpu", "gpu")
+# One embedder per process, so the device is installation-wide: read from the owner's store whoever is asking.
+_device_cached: list = [] # [(monotonic time, value)]
+# Same guard as _generation: a read that overlapped a write must not cache the pre-write value.
+_device_generation = 0
+
+
+def get_stored_embedding_device() -> str:
+ """The device chosen in Settings: ``auto`` when unset, unreadable or unrecognized."""
+ now = time.monotonic()
+ with _lock:
+ if _device_cached and now - _device_cached[0][0] < _CACHE_TTL_S:
+ return _device_cached[0][1]
+ gen = _device_generation
+ from utils.account_context import OWNER, bind_account, reset_account
+
+ token = bind_account(OWNER)
+ try:
+ from storage.studio_db import get_app_setting
+ value = get_app_setting(EMBEDDING_DEVICE_SETTING_KEY, None)
+ except Exception: # noqa: BLE001 - store unavailable: the hardware default
+ value = None
+ finally:
+ reset_account(token)
+ device = value if value in EMBEDDING_DEVICE_CHOICES else "auto"
+ with _lock:
+ if _device_generation == gen:
+ _device_cached[:] = [(now, device)]
+ return device
+
+
+def forget_cached_embedding_device() -> None:
+ global _device_generation
+ with _lock:
+ _device_cached.clear()
+ _device_generation += 1
+
+
+def set_embedding_device(device: str) -> bool:
+ """Persist the device; returns whether it changed, so an unchanged save keeps the embedder resident."""
+ if device not in EMBEDDING_DEVICE_CHOICES:
+ raise ValueError("Device must be auto, cpu or gpu.")
+ forget_cached_embedding_device()
+ if get_stored_embedding_device() == device:
+ return False
+ from storage.studio_db import upsert_app_settings
+ from utils.account_context import OWNER, bind_account, reset_account
+
+ token = bind_account(OWNER)
+ try:
+ upsert_app_settings({EMBEDDING_DEVICE_SETTING_KEY: device}, read_back = False)
+ finally:
+ reset_account(token)
+ forget_cached_embedding_device()
+ return True
diff --git a/studio/frontend/src/features/settings/api/embedding-model.ts b/studio/frontend/src/features/settings/api/embedding-model.ts
index 0d06a86da4e..26d92d95689 100644
--- a/studio/frontend/src/features/settings/api/embedding-model.ts
+++ b/studio/frontend/src/features/settings/api/embedding-model.ts
@@ -19,8 +19,14 @@ export type EmbeddingModelSettings = {
/** ANY embedder is resident, so Unload has something to do. Saving a new model
* does not release the old one, so not the same question as `loaded`. */
backendLoaded: boolean;
+ /** Where the embedder runs, for every embedding model. */
+ embeddingDevice: EmbeddingDevice;
+ /** RAG_EMBED_DEVICE names a device, so the choice is read-only here. */
+ embeddingDeviceLocked: boolean;
};
+export type EmbeddingDevice = "auto" | "cpu" | "gpu";
+
type ApiEmbeddingModelSettings = {
// biome-ignore lint/style/useNamingConvention: API schema
embedding_model: string;
@@ -35,6 +41,10 @@ type ApiEmbeddingModelSettings = {
loaded?: boolean;
// biome-ignore lint/style/useNamingConvention: API schema
backend_loaded?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ embedding_device?: EmbeddingDevice;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ embedding_device_locked?: boolean;
};
/** 409 from the backend: the model could not be verified as an embedding model
@@ -56,6 +66,8 @@ function fromApi(settings: ApiEmbeddingModelSettings): EmbeddingModelSettings {
// A backend predating this field answers only about the selected model,
// which is the old behaviour and the right fallback.
backendLoaded: settings.backend_loaded ?? settings.loaded ?? false,
+ embeddingDevice: settings.embedding_device ?? "auto",
+ embeddingDeviceLocked: settings.embedding_device_locked ?? false,
};
}
@@ -112,6 +124,23 @@ export async function updateEmbeddingModelSettings(
return settings;
}
+/** Moves the embedder to another device; the next index or search reloads it there. */
+export async function updateEmbeddingDevice(
+ device: EmbeddingDevice,
+): Promise<EmbeddingModelSettings> {
+ const res = await authFetch("/api/settings/embedding-model/device", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ device }),
+ });
+ if (!res.ok) {
+ throw new Error(
+ await readFastApiError(res, "Failed to save the embedding device"),
+ );
+ }
+ return fromApi(await res.json());
+}
+
/** What saving a model would need fetched, and whether it is already on disk. */
export type EmbeddingModelResolution = {
embeddingModel: string;
diff --git a/studio/frontend/src/features/settings/components/documents-rag-section.tsx b/studio/frontend/src/features/settings/components/documents-rag-section.tsx
index f58eef78aaf..d1c628f3461 100644
--- a/studio/frontend/src/features/settings/components/documents-rag-section.tsx
+++ b/studio/frontend/src/features/settings/components/documents-rag-section.tsx
@@ -2,6 +2,13 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import { useChatRuntimeStore } from "@/features/chat";
import { formatBytes, listCachedGguf, listCachedModels } from "@/features/hub";
import { Spinner } from "@/components/ui/spinner";
@@ -21,10 +28,12 @@ import { toast } from "@/lib/toast";
import { type ReactElement, useCallback, useEffect, useRef, useState } from "react";
import {
EmbeddingModelBlockedError,
+ type EmbeddingDevice,
type EmbeddingModelResolution,
EmbeddingModelVerificationError,
resolveEmbeddingModel,
unloadEmbeddingModel,
+ updateEmbeddingDevice,
updateEmbeddingModelSettings,
} from "../api/embedding-model";
import { useEmbeddingModelStore } from "../stores/embedding-model-store";
@@ -376,6 +385,21 @@ export function DocumentsRagSection(): ReactElement {
}
};
+ const changeDevice = async (device: EmbeddingDevice) => {
+ if (device === embeddingModel?.embeddingDevice) return;
+ setIsSavingEmbeddingModel(true);
+ try {
+ // Residency, not selection: the model stays, only where it loads next changes.
+ await applyResidency(() => updateEmbeddingDevice(device));
+ } catch (error) {
+ toast.error(t("settings.general.rag.deviceSaveError"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ setIsSavingEmbeddingModel(false);
+ }
+ };
+
return (
<SettingsSection ref={sectionRef} title={t("settings.general.rag.sectionTitle")}>
<SettingsRow
@@ -473,6 +497,33 @@ export function DocumentsRagSection(): ReactElement {
</div>
</div>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.general.rag.device")}
+ description={
+ embeddingModel?.embeddingDeviceLocked
+ ? t("settings.general.rag.deviceLocked", { name: "RAG_EMBED_DEVICE" })
+ : t("settings.general.rag.deviceDescription")
+ }
+ >
+ <Select
+ value={embeddingModel?.embeddingDevice ?? "auto"}
+ disabled={
+ !embeddingModel ||
+ embeddingModel.embeddingDeviceLocked ||
+ isSavingEmbeddingModel
+ }
+ onValueChange={(device) => void changeDevice(device as EmbeddingDevice)}
+ >
+ <SelectTrigger className="w-36" aria-label={t("settings.general.rag.device")}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="auto">{t("settings.general.rag.deviceAuto")}</SelectItem>
+ <SelectItem value="cpu">{t("settings.general.rag.deviceCpu")}</SelectItem>
+ <SelectItem value="gpu">{t("settings.general.rag.deviceGpu")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </SettingsRow>
</SettingsSection>
);
}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 4f12d915cb2..e068bb87139 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1791,6 +1791,14 @@ export const ar = {
switchFailed: "تعذّر تبديل نموذج التضمين",
back: "العودة إلى المصادر",
menuSubtitle: "يشغّل البحث في الملفات",
+ device: "جهاز التضمين",
+ deviceDescription:
+ "مكان تشغيل نموذج التضمين، لكل النماذج. تفهرس GPU مجموعات المستندات الكبيرة أسرع، لكنها تُبقي جزءًا من VRAM مستخدمًا حتى إعادة تشغيل Studio.",
+ deviceAuto: "تلقائي",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "مضبوط بواسطة {name}.",
+ deviceSaveError: "تعذّر تغيير جهاز التضمين",
},
storage: {
sectionTitle: "التخزين",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 09455e0fbe2..79e37ec9b77 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1816,6 +1816,14 @@ export const de = {
switchFailed: "Embedding-Modell konnte nicht gewechselt werden",
back: "Zurück zu den Quellen",
menuSubtitle: "Für die Dateisuche",
+ device: "Embedding-Gerät",
+ deviceDescription:
+ "Wo das Embedding-Modell läuft, für jedes Modell. Die GPU indexiert große Dokumentmengen schneller, belegt aber etwas VRAM bis zum Neustart von Studio.",
+ deviceAuto: "Automatisch",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Festgelegt durch {name}.",
+ deviceSaveError: "Das Embedding-Gerät konnte nicht geändert werden",
},
storage: {
sectionTitle: "Speicher",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index f009a1b70ac..aa33b42f970 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1850,6 +1850,14 @@ export const en = {
switchFailed: "Couldn't switch the embedding model",
back: "Back to sources",
menuSubtitle: "Powers file search",
+ device: "Embedding device",
+ deviceDescription:
+ "Where the embedding model runs, for every model. GPU indexes large document sets faster but keeps some VRAM in use until Studio restarts.",
+ deviceAuto: "Automatic",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Set by {name}.",
+ deviceSaveError: "Couldn't change the embedding device",
},
storage: {
sectionTitle: "Storage",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index fd59561187d..c8aa1b709e0 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1811,6 +1811,14 @@ export const es = {
switchFailed: "No se pudo cambiar el modelo de embedding",
back: "Volver a las fuentes",
menuSubtitle: "Para buscar en archivos",
+ device: "Dispositivo de embeddings",
+ deviceDescription:
+ "Dónde se ejecuta el modelo de embeddings, para todos los modelos. La GPU indexa grandes conjuntos de documentos más rápido, pero mantiene algo de VRAM en uso hasta que Studio se reinicie.",
+ deviceAuto: "Automático",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Definido por {name}.",
+ deviceSaveError: "No se pudo cambiar el dispositivo de embeddings",
},
storage: {
sectionTitle: "Almacenamiento",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index e42b6f5a584..874e26ee951 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1814,6 +1814,14 @@ export const fr = {
switchFailed: "Impossible de changer le modèle d'embedding",
back: "Retour aux sources",
menuSubtitle: "Pour la recherche de fichiers",
+ device: "Appareil d'embedding",
+ deviceDescription:
+ "Où s'exécute le modèle d'embedding, pour tous les modèles. Le GPU indexe plus vite les grands ensembles de documents, mais garde un peu de VRAM occupée jusqu'au redémarrage de Studio.",
+ deviceAuto: "Automatique",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Défini par {name}.",
+ deviceSaveError: "Impossible de changer l'appareil d'embedding",
},
storage: {
sectionTitle: "Stockage",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 01feca41746..d2c2cc8eb2f 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -1893,6 +1893,14 @@ export const he = {
switchFailed: "לא ניתן להחליף את מודל ההטמעה",
back: "חזרה למקורות",
menuSubtitle: "מפעיל את חיפוש הקבצים",
+ device: "התקן הטמעה",
+ deviceDescription:
+ "היכן רץ מודל ההטמעה, לכל המודלים. GPU מאנדקס אוספי מסמכים גדולים מהר יותר, אבל משאיר חלק מה-VRAM בשימוש עד ש-Studio מופעל מחדש.",
+ deviceAuto: "אוטומטי",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "מוגדר על ידי {name}.",
+ deviceSaveError: "לא ניתן היה לשנות את התקן ההטמעה",
},
storage: {
sectionTitle: "אחסון",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 478a38faaed..21f7acf3e85 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1794,6 +1794,14 @@ export const hi = {
switchFailed: "एम्बेडिंग मॉडल नहीं बदला जा सका",
back: "स्रोतों पर वापस जाएँ",
menuSubtitle: "फ़ाइल खोज के लिए",
+ device: "एम्बेडिंग डिवाइस",
+ deviceDescription:
+ "एम्बेडिंग मॉडल कहाँ चलता है, हर मॉडल के लिए। GPU बड़े दस्तावेज़ संग्रह तेज़ी से इंडेक्स करता है, लेकिन Studio के रीस्टार्ट होने तक कुछ VRAM इस्तेमाल में रखता है।",
+ deviceAuto: "स्वचालित",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "{name} द्वारा सेट।",
+ deviceSaveError: "एम्बेडिंग डिवाइस नहीं बदला जा सका",
},
storage: {
sectionTitle: "स्टोरेज",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index dca424ba4bc..03dafbf51fb 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1793,6 +1793,14 @@ export const it = {
switchFailed: "Impossibile cambiare il modello di embedding",
back: "Torna alle fonti",
menuSubtitle: "Per la ricerca nei file",
+ device: "Dispositivo di embedding",
+ deviceDescription:
+ "Dove viene eseguito il modello di embedding, per ogni modello. La GPU indicizza più velocemente grandi raccolte di documenti, ma tiene occupata un po' di VRAM fino al riavvio di Studio.",
+ deviceAuto: "Automatico",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Impostato da {name}.",
+ deviceSaveError: "Impossibile cambiare il dispositivo di embedding",
},
storage: {
sectionTitle: "Archiviazione",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 65ce1ea44c0..d6b33da9a6d 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1776,6 +1776,14 @@ export const ja = {
switchFailed: "埋め込みモデルを切り替えられませんでした",
back: "ソースに戻る",
menuSubtitle: "ファイル検索に使用",
+ device: "埋め込みデバイス",
+ deviceDescription:
+ "すべてのモデルで埋め込みモデルを実行する場所です。GPU は大量のドキュメントをより速くインデックスしますが、Studio を再起動するまで一部の VRAM を使用し続けます。",
+ deviceAuto: "自動",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "{name} で設定されています。",
+ deviceSaveError: "埋め込みデバイスを変更できませんでした",
},
storage: {
sectionTitle: "ストレージ",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 1a1fa4d9fcc..f603712fc85 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1787,6 +1787,14 @@ export const ko = {
switchFailed: "임베딩 모델을 전환하지 못했습니다",
back: "소스로 돌아가기",
menuSubtitle: "파일 검색에 사용",
+ device: "임베딩 장치",
+ deviceDescription:
+ "모든 모델에서 임베딩 모델이 실행되는 위치입니다. GPU는 대량의 문서를 더 빠르게 색인하지만 Studio를 다시 시작할 때까지 일부 VRAM을 계속 사용합니다.",
+ deviceAuto: "자동",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "{name}(으)로 설정됨.",
+ deviceSaveError: "임베딩 장치를 변경할 수 없습니다",
},
storage: {
sectionTitle: "저장소",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 62066f37ff1..cd98e338264 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1803,6 +1803,14 @@ export const ptBR = {
switchFailed: "Não foi possível trocar o modelo de embedding",
back: "Voltar às fontes",
menuSubtitle: "Para busca em arquivos",
+ device: "Dispositivo de embeddings",
+ deviceDescription:
+ "Onde o modelo de embeddings é executado, para todos os modelos. A GPU indexa grandes conjuntos de documentos mais rápido, mas mantém um pouco de VRAM em uso até o Studio reiniciar.",
+ deviceAuto: "Automático",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Definido por {name}.",
+ deviceSaveError: "Não foi possível alterar o dispositivo de embeddings",
},
storage: {
sectionTitle: "Armazenamento",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index eeb2c263ce0..58ab0732faf 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1796,6 +1796,14 @@ export const ru = {
switchFailed: "Не удалось сменить модель эмбеддингов",
back: "Назад к источникам",
menuSubtitle: "Для поиска по файлам",
+ device: "Устройство для эмбеддингов",
+ deviceDescription:
+ "Где работает модель эмбеддингов, для любой модели. GPU быстрее индексирует большие наборы документов, но занимает часть VRAM до перезапуска Studio.",
+ deviceAuto: "Автоматически",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Задано через {name}.",
+ deviceSaveError: "Не удалось изменить устройство для эмбеддингов",
},
storage: {
sectionTitle: "Хранилище",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 37bb726cd8f..f4305bbe280 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -1962,6 +1962,14 @@ export const sv = {
switchFailed: "Kunde inte byta inbäddningsmodell",
back: "Tillbaka till källor",
menuSubtitle: "Används för filsökning",
+ device: "Enhet för inbäddning",
+ deviceDescription:
+ "Var inbäddningsmodellen körs, för alla modeller. GPU indexerar stora dokumentmängder snabbare men håller en del VRAM upptaget tills Studio startas om.",
+ deviceAuto: "Automatiskt",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "Anges av {name}.",
+ deviceSaveError: "Det gick inte att ändra enheten för inbäddning",
},
storage: {
sectionTitle: "Lagring",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index db2929b3ebe..2b5c364656e 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1769,6 +1769,14 @@ export const zhCN = {
switchFailed: "无法切换嵌入模型",
back: "返回来源",
menuSubtitle: "用于文件搜索",
+ device: "嵌入设备",
+ deviceDescription:
+ "嵌入模型的运行位置,适用于所有模型。GPU 索引大量文档更快,但在 Studio 重启前会占用部分显存。",
+ deviceAuto: "自动",
+ deviceCpu: "CPU",
+ deviceGpu: "GPU",
+ deviceLocked: "由 {name} 设置。",
+ deviceSaveError: "无法更改嵌入设备",
},
storage: {
sectionTitle: "存储",
diff --git a/studio/frontend/tests/embedding-model-store.test.ts b/studio/frontend/tests/embedding-model-store.test.ts
index a67a0284001..e5ef24e7e11 100644
--- a/studio/frontend/tests/embedding-model-store.test.ts
+++ b/studio/frontend/tests/embedding-model-store.test.ts
@@ -23,6 +23,8 @@ type Settings = {
isCustom: boolean;
loaded: boolean;
backendLoaded: boolean;
+ embeddingDevice: "auto" | "cpu" | "gpu";
+ embeddingDeviceLocked: boolean;
};
function settings(model: string): Settings {
@@ -34,6 +36,8 @@ function settings(model: string): Settings {
isCustom: model !== "unsloth/bge-small-en-v1.5",
loaded: false,
backendLoaded: false,
+ embeddingDevice: "auto",
+ embeddingDeviceLocked: false,
};
}