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: serve decision models through the MLX engine on Apple Silicon (#13015)

Long Yixingfde93c4fb0eb
diff --git a/studio/backend/core/systemone/catalog.py b/studio/backend/core/systemone/catalog.py
index 3ac1bf333bf..e8305d0db5f 100644
--- a/studio/backend/core/systemone/catalog.py
+++ b/studio/backend/core/systemone/catalog.py
@@ -24,7 +24,8 @@ class Checkpoint:
# "laya" (rl_agent_config.json + encoder), "clef" (Qwen3.5 backbone + joint schema head), or
# "gguf" (a GGUF_COMPANIONS entry llama.cpp serves, with no PyTorch form).
layout: str = "laya"
- # "pytorch", or "llama.cpp" for the GGUF a Clef entry is served from (see laya_runtime._native_target).
+ # "pytorch", "llama.cpp" for the GGUF a Clef entry is served from (see laya_runtime._native_target), or
+ # "mlx" for the form unsloth-zoo's MLX engine serves on Apple Silicon (see laya_runtime._mlx_target).
backend: str = "pytorch"
# The served GGUF files of a local export, so a re-export is a different checkpoint to a resident server.
revision: str | None = None
@@ -253,6 +254,127 @@ GGUF_COMPANIONS = {
},
}
+
+@dataclass(frozen = True)
+class MlxCompanion:
+ """The source repo unsloth-zoo's MLX decision engine reads on Apple Silicon in place of an entry's GGUF."""
+
+ family: str
+ repo: str
+ revision: str
+ files: tuple[str, ...]
+ download_bytes: int
+ # The language model an adapter is merged into at load, in its own repo.
+ base: MlxCompanion | None = None
+
+
+def _qwen_base(repo: str, revision: str, shards: int, size: int, *extra: str) -> MlxCompanion:
+ files = (
+ "config.json",
+ "tokenizer.json",
+ "tokenizer_config.json",
+ "vocab.json",
+ "merges.txt",
+ "preprocessor_config.json",
+ "video_preprocessor_config.json",
+ "model.safetensors.index.json",
+ *extra,
+ *(f"model.safetensors-{i:05d}-of-{shards:05d}.safetensors" for i in range(1, shards + 1)),
+ )
+ return MlxCompanion("", repo, revision, files, size)
+
+
+_ADAPTER_FILES = ("adapter_config.json", "adapter_model.safetensors")
+
+MLX_COMPANIONS = {
+ "julia-1": MlxCompanion(
+ "laya",
+ "SupersonicLabs/Julia-1",
+ "a85b127321d580d65176c89ced8273f305745d85",
+ (
+ "julia_config.json",
+ "model.safetensors",
+ "encoder/config.json",
+ "tokenizer/tokenizer.json",
+ "tokenizer/tokenizer_config.json",
+ ),
+ 611_554_979,
+ ),
+ "lev": MlxCompanion(
+ "lev",
+ "interfaze-ai/lev",
+ "7bdc748dffebd85b57ee0dbea8f994c6354fed31",
+ (*_ADAPTER_FILES, "lev_release.json", "calibration.json"),
+ 169_905_572,
+ base = _qwen_base(
+ "Qwen/Qwen3.5-4B",
+ "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a",
+ 2,
+ 9_342_816_694,
+ "chat_template.jinja",
+ ),
+ ),
+ "kev-0.8b": MlxCompanion(
+ "kev",
+ "jaredpalmer/kev-0.8b",
+ "bf75a6a8848ea6960ff2ed108d9ed44c2941174f",
+ (*_ADAPTER_FILES, "head.pt", "training_config.json"),
+ 45_445_663,
+ base = _qwen_base(
+ "Qwen/Qwen3.5-0.8B-Base", "dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68", 1, 1_769_897_109
+ ),
+ ),
+ "kev-4b": MlxCompanion(
+ "kev",
+ "jaredpalmer/kev-4b",
+ "6cfce5c2fa4b4bd64026336ab649c5ca78857d52",
+ (*_ADAPTER_FILES, "head.pt", "training_config.json"),
+ 135_176_939,
+ base = _qwen_base(
+ "Qwen/Qwen3.5-4B-Base", "1001bb4d826a52d1f399e183466143f4da7b741b", 2, 9_342_808_116
+ ),
+ ),
+ "kev-9b": MlxCompanion(
+ "kev",
+ "jaredpalmer/kev-9b",
+ "db029f08b290afd9fee4aa4bbcd9ae48602d1eb0",
+ (*_ADAPTER_FILES, "head.pt", "training_config.json"),
+ 181_576_197,
+ base = _qwen_base(
+ "Qwen/Qwen3.5-9B-Base", "68c46c4b3498877f3ef123c856ecfde50c39f404", 4, 19_329_294_358
+ ),
+ ),
+ "bespoke-nimble-9b-v3": MlxCompanion(
+ "nimble",
+ "bespokelabs/Bespoke-Nimble-9B-v3",
+ "8e927b9b4afdbb14479fac10a7364d1a695be208",
+ (*_ADAPTER_FILES, "schema_config.json"),
+ 692_535_920,
+ base = _qwen_base(
+ "Qwen/Qwen3.5-9B",
+ "c202236235762e1c871ad0ccb60c8ee5ba337b9a",
+ 4,
+ 19_329_302_904,
+ "chat_template.jinja",
+ ),
+ ),
+ # The 8-bit MLX conversion, the closest in size and answers to the Q8_0 GGUF; text only.
+ "openjev": MlxCompanion(
+ "openjev",
+ "openjev/openjev-MLX",
+ "a9dcc20aa827a6c7eae478f6ebb3b255bb135451",
+ (
+ "config.json",
+ "tokenizer.json",
+ "tokenizer_config.json",
+ "chat_template.jinja",
+ "model.safetensors.index.json",
+ *(f"model-{i:05d}-of-00006.safetensors" for i in range(1, 7)),
+ ),
+ 28_599_913_943,
+ ),
+}
+
# Names TypeSafe's and OpenJev's SDKs send by default, so an unmodified client reaches the configured model.
DEFAULT_ALIASES = frozenset({"default", "laya", "jev-latest", "jev-preview", "openjev-latest"})
LOCAL_NAME = "laya-local"
diff --git a/studio/backend/core/systemone/laya_runtime.py b/studio/backend/core/systemone/laya_runtime.py
index 8c96a81ecac..b06d5a6c8df 100644
--- a/studio/backend/core/systemone/laya_runtime.py
+++ b/studio/backend/core/systemone/laya_runtime.py
@@ -15,7 +15,7 @@ import time
from pathlib import Path
from typing import Any
-from .catalog import CHECKPOINTS, GGUF_COMPANIONS, LOCAL_NAME, Checkpoint
+from .catalog import CHECKPOINTS, GGUF_COMPANIONS, LOCAL_NAME, MLX_COMPANIONS, Checkpoint
logger = logging.getLogger(__name__)
@@ -36,7 +36,7 @@ _loaded: Checkpoint | None = None
_device_name: str | None = None
_loader: threading.Thread | None = None
_loading: Checkpoint | None = None
-# A llama.cpp load that holds (or is taking) the GPU claim, until its agent is published or dropped.
+# A llama.cpp or MLX engine load that holds (or is taking) the GPU claim, until its agent is published or dropped.
_gpu_load = False
_failure: tuple[Checkpoint, str, float] | None = None
_import_lock = threading.Lock()
@@ -118,6 +118,7 @@ def _wanted(path: str, subfolder: str | None) -> bool:
LLAMA_CPP = "llama.cpp"
+MLX = "mlx"
GGUF = "gguf"
@@ -125,6 +126,136 @@ def _is_native(checkpoint) -> bool:
return getattr(checkpoint, "backend", "pytorch") == LLAMA_CPP
+def _is_mlx(checkpoint) -> bool:
+ return getattr(checkpoint, "backend", None) == MLX
+
+
+def _arbitrated(served) -> bool:
+ """A llama.cpp server or an MLX engine model: the GPU arbiter can end it, and it unloads when idle."""
+ return getattr(served, "backend", None) in (LLAMA_CPP, MLX)
+
+
+def _engine_available() -> bool:
+ """Apple Silicon with an unsloth-zoo that serves every decision family, and the GPU as where decoders run."""
+ try:
+ from utils.hardware import hardware
+
+ # Only a finished detection, as clef_unsupported_reason(wait = False): a settings read never waits on it.
+ if not hardware.DETECTION_COMPLETE.is_set() or hardware.DEVICE != hardware.DeviceType.MLX:
+ return False
+ if not _native_gpu():
+ return False
+ from unsloth_zoo.mlx.decision import DecisionRequestError # noqa: F401
+ except Exception:
+ return False
+ return True
+
+
+def _mlx_target(checkpoint: Checkpoint) -> Checkpoint | None:
+ """What unsloth-zoo's MLX engine serves in process on Apple Silicon: a merged Clef's own folder, or the source repo of a GGUF entry."""
+ if _is_mlx(checkpoint) or not _engine_available():
+ return None
+ if checkpoint.layout == "clef":
+ if checkpoint.is_local:
+ from utils.models.model_config import clef_folder_kind
+ if clef_folder_kind(Path(checkpoint.source).expanduser()) != "merged":
+ return None
+ return dataclasses.replace(checkpoint, backend = MLX)
+ companion = MLX_COMPANIONS.get(checkpoint.name)
+ if companion is None or CHECKPOINTS.get(checkpoint.name) != checkpoint:
+ return None
+ return dataclasses.replace(
+ checkpoint,
+ source = companion.repo,
+ download_bytes = sum(repo.download_bytes for repo in _mlx_repos(companion)),
+ backend = MLX,
+ revision = companion.revision,
+ )
+
+
+def _mlx_repos(companion) -> tuple:
+ return (companion.base, companion) if companion.base else (companion,)
+
+
+def _mlx_family(checkpoint: Checkpoint) -> str:
+ return "clef" if checkpoint.layout == "clef" else MLX_COMPANIONS[checkpoint.name].family
+
+
+def _wants_gpu(checkpoint) -> bool:
+ """Whether loading this takes the GPU through the arbiter; an MLX encoder sits beside a chat model, as Laya does."""
+ if _is_mlx(checkpoint):
+ return _mlx_family(checkpoint) != "laya"
+ return _is_native(checkpoint) and _native_gpu()
+
+
+def _repo_dir(repo, local_only: bool) -> Path:
+ from huggingface_hub import snapshot_download
+
+ from utils.hf_cache_settings import active_hf_hub_cache
+ from utils.utils import hf_env_offline
+
+ def fetch(revision, local: bool) -> Path | None:
+ try:
+ folder = Path(
+ snapshot_download(
+ repo.repo,
+ revision = revision,
+ cache_dir = active_hf_hub_cache(),
+ local_files_only = local,
+ allow_patterns = list(repo.files),
+ )
+ )
+ except Exception:
+ if not local:
+ raise
+ return None
+ return folder if all((folder / name).is_file() for name in repo.files) else None
+
+ # A settings download fetches the repo's main, which serves where the pinned revision is not complete.
+ folder = fetch(repo.revision, True) or fetch(None, True)
+ if folder is None and not (local_only or hf_env_offline()):
+ folder = fetch(repo.revision, False)
+ if folder is None:
+ raise FileNotFoundError(f"{repo.repo} is not downloaded")
+ return folder
+
+
+def _repo_cached(repo) -> bool:
+ try:
+ _repo_dir(repo, local_only = True)
+ except Exception:
+ return False
+ return True
+
+
+def _mlx_dirs(checkpoint: Checkpoint, local_only: bool) -> tuple[Path, Path | None]:
+ """(model folder, base folder) of an MLX target."""
+ if checkpoint.layout == "clef":
+ return _clef_dir(checkpoint, local_only), None
+ folders = [_repo_dir(repo, local_only) for repo in _mlx_repos(MLX_COMPANIONS[checkpoint.name])]
+ return folders[-1], (folders[0] if len(folders) > 1 else None)
+
+
+def _mlx_choice(checkpoint: Checkpoint, images, questions, preference: str) -> Checkpoint | None:
+ """Auto on Apple Silicon answers text through the MLX engine, unless only the llama.cpp form is at hand."""
+ from .native_worker import request_gap
+
+ if preference != "auto" or images or request_gap(questions or {}) is not None:
+ return None
+ if (target := _mlx_target(checkpoint)) is None:
+ return None
+ if _loaded == target and _agent is not None:
+ return target
+ native = _native_target(checkpoint)
+ if native is not None and _native_unavailable(checkpoint, native) is None:
+ # A resident llama.cpp server keeps answering, and a downloaded GGUF serves before the MLX form is fetched.
+ if _loaded == native and _agent is not None:
+ return None
+ if not native.is_local and is_cached(native) and not is_cached(target):
+ return None
+ return target
+
+
def _native_target(checkpoint: Checkpoint) -> Checkpoint | None:
"""The llama.cpp form of an entry: ggml-org's GGUF for a stock Clef, a current export for a folder, a GGUF entry itself."""
if checkpoint.layout == GGUF:
@@ -246,16 +377,24 @@ def select(
images = None,
questions = None,
preference: str | None = None,
+ state_images: bool = False,
) -> tuple[Checkpoint, str | None]:
"""(what serves this request, why Auto did not pick llama.cpp); raises for what nothing here can serve.
- Auto takes llama.cpp when the entry has a GGUF and Studio's llama-server serves decisions, else PyTorch.
- Images are llama.cpp only. Laya is always served by PyTorch, a GGUF entry always by llama.cpp.
+ Auto takes llama.cpp when the entry has a GGUF and Studio's llama-server serves decisions, else PyTorch;
+ on Apple Silicon it answers text through unsloth-zoo's MLX engine first.
+ Images are llama.cpp only. Laya is always served by PyTorch, a GGUF entry otherwise by llama.cpp.
"""
from utils.systemone_settings import get_backend
from .native_worker import request_gap
+ if (preference or get_backend()) == MLX and checkpoint.layout in ("clef", GGUF):
+ return _select_mlx(checkpoint, images or state_images), None
+ # Images in the state keep a request off MLX only: every other route reads them as before.
+ mlx = _mlx_choice(checkpoint, images or state_images, questions, preference or get_backend())
+ if mlx is not None:
+ return mlx, None
if checkpoint.layout == GGUF:
return _select_gguf(checkpoint, questions, preference or get_backend()), None
if checkpoint.layout != "clef":
@@ -300,6 +439,23 @@ def select(
return checkpoint, reason
+def _select_mlx(checkpoint: Checkpoint, images) -> Checkpoint:
+ """The MLX runtime answers through the engine or not at all, whatever llama.cpp has loaded or downloaded."""
+ if images:
+ raise Unavailable(
+ 400,
+ "api_usage_error",
+ "Images are served only by llama.cpp; set the Decision API runtime to Auto or llama.cpp.",
+ )
+ if not _engine_available():
+ reason = "The MLX runtime needs Apple Silicon with the Decision API on the GPU."
+ elif (target := _mlx_target(checkpoint)) is not None:
+ return target
+ else:
+ reason = f"{checkpoint.name} has no MLX form."
+ raise Unavailable(400, "api_usage_error", f"{reason} Set the Decision API runtime to Auto.")
+
+
def _select_gguf(checkpoint: Checkpoint, questions, preference: str) -> Checkpoint:
from .native_worker import request_gap
@@ -345,6 +501,21 @@ def effective_backend(checkpoint) -> tuple[str | None, str | None]:
return target.backend, reason
+def mlx_available() -> bool:
+ """Whether the MLX runtime can be chosen here."""
+ return _engine_available()
+
+
+def mlx_ready(checkpoint) -> bool:
+ """Whether the MLX engine could serve this entry here under the runtime setting."""
+ from utils.systemone_settings import get_backend
+ return (
+ isinstance(checkpoint, Checkpoint)
+ and get_backend() in ("auto", MLX)
+ and _mlx_target(checkpoint) is not None
+ )
+
+
def native_ready(checkpoint) -> bool:
"""Whether llama.cpp could serve this Clef or GGUF entry here under the runtime setting."""
if not isinstance(checkpoint, Checkpoint) or checkpoint.layout == "laya":
@@ -352,7 +523,7 @@ def native_ready(checkpoint) -> bool:
from utils.systemone_settings import get_backend
native = _native_target(checkpoint)
- return get_backend() != "pytorch" and _native_unavailable(checkpoint, native) is None
+ return get_backend() in ("auto", LLAMA_CPP) and _native_unavailable(checkpoint, native) is None
def input_modalities(checkpoint) -> list[str]:
@@ -511,6 +682,12 @@ def _utf8_open(
def is_cached(checkpoint: Checkpoint) -> bool:
+ if _is_mlx(checkpoint):
+ try:
+ _mlx_dirs(checkpoint, local_only = True)
+ except Exception:
+ return False
+ return True
if _is_native(checkpoint):
try:
_native_files(checkpoint, local_only = True)
@@ -527,12 +704,39 @@ def is_cached(checkpoint: Checkpoint) -> bool:
return all((folder / name).is_file() for name in _WEIGHT_FILES)
+def _mlx_plan(checkpoint: Checkpoint) -> dict[str, Any]:
+ # One repo per plan, the base first; the settings page asks again once that download is done.
+ cached = is_cached(checkpoint)
+ repos = _mlx_repos(MLX_COMPANIONS[checkpoint.name])
+ repo = repos[-1] if cached else next((r for r in repos if not _repo_cached(r)), repos[-1])
+ return {
+ "repo": repo.repo,
+ "revision": repo.revision,
+ "files": sorted(repo.files),
+ "size_bytes": repo.download_bytes,
+ "cached": cached,
+ "error": None,
+ }
+
+
def download_plan(checkpoint: Checkpoint, preference: str | None = None) -> dict[str, Any]:
- if checkpoint.layout == "clef" and not _is_native(checkpoint):
+ if not _is_mlx(checkpoint) and (checkpoint.layout == GGUF or not _is_native(checkpoint)):
try:
checkpoint = select(checkpoint, preference = preference)[0]
- except Unavailable:
- pass
+ except Unavailable as exc:
+ from utils.systemone_settings import get_backend
+
+ # The MLX runtime has no other form to fall back to, so nothing is offered for download.
+ if (preference or get_backend()) == MLX:
+ return {
+ "repo": None,
+ "files": [],
+ "size_bytes": 0,
+ "cached": False,
+ "error": exc.message,
+ }
+ if _is_mlx(checkpoint) and checkpoint.layout == GGUF:
+ return _mlx_plan(checkpoint)
cached = is_cached(checkpoint)
plan = {"repo": None, "files": [], "size_bytes": 0, "cached": cached, "error": None}
if checkpoint.name == LOCAL_NAME or checkpoint.is_local:
@@ -592,12 +796,14 @@ def _close(agent, release_gpu: bool = True) -> None:
# A Clef agent is a worker process; ending it returns its GPU memory.
if agent is not None and hasattr(agent, "close"):
agent.close()
- if release_gpu and _is_native(agent) and getattr(agent, "gpu", False):
+ if release_gpu and _arbitrated(agent) and getattr(agent, "gpu", False):
from core.inference import gpu_arbiter
def unclaimed() -> bool:
# A newer server loading or resident while this one closed keeps the claim.
with _state_lock:
- return not _gpu_load and not (_is_native(_loaded) and getattr(_agent, "gpu", False))
+ return not _gpu_load and not (
+ _arbitrated(_loaded) and getattr(_agent, "gpu", False)
+ )
gpu_arbiter.release_if(gpu_arbiter.DECISIONS, unclaimed)
@@ -648,9 +854,113 @@ class _MLXAgent:
self.model = load_decision_model(folder, **({"compute_dtype": self.dtype} if mixed else {}))
+_ENGINE_TOKENS = 16384
+
+
+class _EngineAgent:
+ """An unsloth-zoo MLX decision model that builds its own prompts from the request."""
+
+ device = backend = MLX
+
+ def __init__(self, folder: Path, family: str, base: Path | None):
+ from unsloth_zoo.mlx.decision import load_decision_model
+
+ self.gpu = family != "laya"
+ self.model = load_decision_model(folder, family = family, base_model = base)
+ # An encoder reads one question at a time, and its window is the encoder's (Julia-1: 8192).
+ self.positions = None
+ encoder = folder / "encoder" / "config.json"
+ if family == "laya" and encoder.is_file():
+ import json
+ self.positions = json.loads(encoder.read_text(encoding = "utf-8")).get(
+ "max_position_embeddings"
+ )
+
+ def close(self) -> None:
+ # A request that still holds this agent must not keep the weights on the GPU another owner now has.
+ self.model = None
+ _release_memory()
+
+ def decide(self, state, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
+ from unsloth_zoo.mlx.decision import DecisionRequestError, DecisionUnsupportedError
+
+ # As on llama.cpp, a question without instructions is asked by its id.
+ questions = {
+ name: {**q, "instructions": str(name)} if q.get("instructions") in (None, "") else q
+ for name, q in questions.items()
+ }
+ import json
+
+ # The engine has no length limit of its own. This bounds its memory by the request as sent: each family lays the
+ # state and questions out its own way, so what the model reads can differ from this count by the layout's overhead.
+ text = state if isinstance(state, str) else json.dumps(state, ensure_ascii = False)
+ text += json.dumps(questions, ensure_ascii = False)
+ tokenizer = getattr(self.model, "tokenizer", None)
+ if tokenizer is not None:
+ ids = tokenizer.encode(text, add_special_tokens = False)
+ if len(getattr(ids, "ids", ids)) > _ENGINE_TOKENS:
+ raise Unavailable(
+ 422,
+ "invalid_request_error",
+ f"State and questions are longer than {_ENGINE_TOKENS} tokens. Shorten them.",
+ )
+ if self.positions:
+ # [cls] question [sep] options (with the question, at most max_head) [sep] state [sep], as unsloth-zoo lays it out.
+ state_text = (
+ state if isinstance(state, str) else json.dumps(state, ensure_ascii = False)
+ )
+ read = tokenizer.encode(state_text, add_special_tokens = False)
+ limit = int(self.positions) - int(getattr(self.model, "max_head", 0)) - 4
+ if len(getattr(read, "ids", read)) > limit:
+ raise Unavailable(
+ 422,
+ "invalid_request_error",
+ f"The state is longer than the {limit} tokens this model reads beside a question. Shorten it.",
+ )
+ try:
+ return self.model.answer(state, questions)
+ except DecisionUnsupportedError as exc:
+ raise Unavailable(501, "not_supported_error", str(exc)) from None
+ except DecisionRequestError as exc:
+ raise Unavailable(422, "invalid_request_error", str(exc)) from None
+
+
+def _load_mlx(checkpoint: Checkpoint):
+ global _gpu_load
+ from core.inference import gpu_arbiter
+
+ # Fetched before the eviction, so a failed download leaves the resident model serving.
+ folder, base = _mlx_dirs(checkpoint, local_only = False)
+ _evict()
+ gpu = _wants_gpu(checkpoint)
+ if gpu:
+ with _state_lock:
+ _gpu_load = True
+ try:
+ gpu_arbiter.acquire_for(gpu_arbiter.DECISIONS, allow_evict = False)
+ except gpu_arbiter.GpuOwnerBusyError:
+ raise RuntimeError(_GPU_BUSY.format(checkpoint.name)) from None
+ agent = None
+ try:
+ agent = _EngineAgent(folder, _mlx_family(checkpoint), base)
+ if _training_active():
+ raise RuntimeError(
+ f"{checkpoint.name} needs the GPU, which a training run took while it loaded."
+ )
+ except BaseException:
+ if agent is not None:
+ agent.close()
+ if gpu:
+ gpu_arbiter.release(gpu_arbiter.DECISIONS)
+ raise
+ return agent, MLX
+
+
def _load_checkpoint(checkpoint: Checkpoint):
from utils.systemone_settings import get_device as preferred_device
+ if _is_mlx(checkpoint):
+ return _load_mlx(checkpoint)
if _is_native(checkpoint):
return _load_native(checkpoint)
root = _checkpoint_dir(checkpoint)
@@ -711,7 +1021,7 @@ def _load_native(checkpoint: Checkpoint):
try:
gpu_arbiter.acquire_for(gpu_arbiter.DECISIONS, allow_evict = False)
except gpu_arbiter.GpuOwnerBusyError:
- raise NativeError(_GPU_BUSY) from None
+ raise NativeError(_GPU_BUSY.format("a decision model through llama.cpp")) from None
try:
agent = NativeClefAgent(
model,
@@ -736,7 +1046,7 @@ def _load_native(checkpoint: Checkpoint):
return agent, agent.device
-_GPU_BUSY = "Unload the resident chat, image or video model before serving a decision model through llama.cpp on the GPU."
+_GPU_BUSY = "Unload the resident chat, image or video model before serving {} on the GPU."
_build_lock = threading.Lock()
@@ -945,17 +1255,25 @@ def _hub_download_active(checkpoint: Checkpoint) -> bool:
return False
try:
from hub.utils.download_registry import get_models_registry
- if not get_models_registry().active_job_refs(checkpoint.source):
+ registry = get_models_registry()
+ if not any(registry.active_job_refs(repo) for repo in _sources(checkpoint)):
return False
except Exception:
return False
return not is_cached(checkpoint)
+def _sources(checkpoint: Checkpoint) -> tuple[str, ...]:
+ """The repos a load reads: an MLX adapter's base as well as its own."""
+ if _is_mlx(checkpoint) and checkpoint.layout == GGUF:
+ return tuple(repo.repo for repo in _mlx_repos(MLX_COMPANIONS[checkpoint.name]))
+ return (checkpoint.source,)
+
+
def loading_repo_ids() -> tuple[str, ...]:
with _state_lock:
if _loading is not None and not _loading.is_local:
- return (_loading.source,)
+ return _sources(_loading)
return ()
@@ -986,7 +1304,7 @@ def _load(checkpoint: Checkpoint) -> None:
logger.info("System One dropped %s: it was unloaded while it loaded", checkpoint.name)
_close(agent)
return
- if _is_native(checkpoint):
+ if _arbitrated(checkpoint):
_schedule_idle_unload(generation)
logger.info(
"System One loaded %s on %s in %.1fs",
@@ -1016,7 +1334,7 @@ def _idle_unload(generation: int) -> None:
_schedule_idle_unload(generation)
return
try:
- if _generation != generation or not _is_native(_loaded):
+ if _generation != generation or not _arbitrated(_loaded):
return
idle = time.monotonic() - _last_used
if idle < IDLE_UNLOAD_S:
@@ -1027,22 +1345,22 @@ def _idle_unload(generation: int) -> None:
_unloads += 1
finally:
_run_lock.release()
- logger.info("System One unloaded the idle llama.cpp decision server")
+ logger.info("System One unloaded the idle decision model")
_close(agent)
def evict_for_gpu() -> None:
- """GPU arbiter evictor: ends an idle llama.cpp decision server; refuses while it loads or decides."""
+ """GPU arbiter evictor: ends an idle llama.cpp server or MLX engine model; refuses while it loads or decides."""
global _agent, _loaded, _device_name, _generation, _unloads
from core.inference.gpu_arbiter import DECISIONS, GpuOwnerBusyError
with _state_lock:
- if _is_native(_loading):
+ if _arbitrated(_loading):
raise GpuOwnerBusyError(DECISIONS)
if not _run_lock.acquire(blocking = False):
raise GpuOwnerBusyError(DECISIONS)
try:
- if not _is_native(_loaded):
+ if not _arbitrated(_loaded):
return
agent, _agent, _loaded, _device_name = _agent, None, None, None
_generation += 1
@@ -1065,11 +1383,11 @@ def _clef_blocked_by_training(checkpoint: Checkpoint) -> None:
return
from .catalog import clef_unsupported_reason
- native = _is_native(checkpoint)
- # llama.cpp also serves Clef on CPU, Metal or Vulkan; the PyTorch worker needs CUDA or ROCm.
+ native = _arbitrated(checkpoint)
+ # llama.cpp also serves Clef on CPU, Metal or Vulkan, and MLX on Apple Silicon; the PyTorch worker needs CUDA or ROCm.
if not native and (reason := clef_unsupported_reason()) is not None:
raise Unavailable(400, "api_usage_error", reason)
- if (native and not _native_gpu()) or not _training_active():
+ if (_is_native(checkpoint) and not _native_gpu()) or not _training_active():
return
# Clef has no CPU fallback: it waits for the GPU instead of taking it from the run.
# Only a resident on the GPU: a llama.cpp server on CPU keeps serving during the run.
@@ -1091,10 +1409,13 @@ def _ensure_loading(checkpoint: Checkpoint) -> threading.Thread | None:
with _state_lock:
if _loaded == checkpoint and _agent is not None and not misplaced:
return None
- if _is_native(checkpoint) and _native_gpu():
+ if _wants_gpu(checkpoint):
from core.inference.gpu_arbiter import DECISIONS, current_owner
if current_owner() not in (None, DECISIONS):
- raise Unavailable(409, "gpu_busy", _GPU_BUSY, retry_after = 1)
+ busy = _GPU_BUSY.format(
+ checkpoint.name if _is_mlx(checkpoint) else "a decision model through llama.cpp"
+ )
+ raise Unavailable(409, "gpu_busy", busy, retry_after = 1)
if _failure and _failure[0] == checkpoint and time.monotonic() < _failure[2]:
raise Unavailable(
503,
@@ -1734,7 +2055,13 @@ def _route(checkpoint: Checkpoint, state, questions, images) -> dict[str, Any]:
from .clef_runtime import MAX_LENGTH
from .native_worker import NativeContextOverflow
- target, reason = select(checkpoint, images, questions)
+ from utils.hardware import hardware
+
+ if checkpoint.layout != "laya" and hardware.is_apple_silicon():
+ # A request, unlike a settings read, waits for device detection, so the first one already knows of MLX.
+ hardware.get_device()
+ state_images = _state_has_images(state)
+ target, reason = select(checkpoint, images, questions, state_images = state_images)
if checkpoint.layout != "laya":
_fallback_reason = reason
try:
@@ -1757,13 +2084,24 @@ def _route(checkpoint: Checkpoint, state, questions, images) -> dict[str, Any]:
# A llama-server that turned out not to serve decisions: Auto answers this request on PyTorch.
if not _is_native(target) or get_backend() != "auto" or images:
raise
- retry, reason = select(checkpoint, images, questions)
+ retry, reason = select(checkpoint, images, questions, state_images = state_images)
if retry == target:
raise
_fallback_reason = reason
return _decide(retry, state, questions, None)
+def _state_has_images(state) -> bool:
+ """Image parts of a chat-message state, which llama.cpp reads and the MLX engine refuses (as unsloth-zoo scans them)."""
+ messages = state.get("messages") if isinstance(state, dict) else state
+ for message in messages if isinstance(messages, list) else []:
+ content = message.get("content") if isinstance(message, dict) else None
+ for part in content if isinstance(content, list) else []:
+ if isinstance(part, dict) and part.get("type") == "image_url":
+ return True
+ return False
+
+
def _decide(
checkpoint: Checkpoint,
state,
@@ -1783,6 +2121,16 @@ def _decide(
result = _decide_native(checkpoint, agent, state, questions, images)
_last_used = time.monotonic()
return result
+ if _is_mlx(checkpoint):
+ result = agent.decide(state, questions)
+ _last_used = time.monotonic()
+ return {
+ "model": checkpoint.name,
+ "answers": {name: _wire_answer(result["answers"][name]) for name in questions},
+ "usage": {"input_tokens": int(result["usage"]["input_tokens"]), "output_tokens": 0},
+ "truncated": False,
+ "_backend": MLX,
+ }
if checkpoint.layout == "clef":
return _decide_clef(checkpoint, agent, state, questions)
laya_questions = {name: _to_laya(q) for name, q in questions.items()}
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index b328924fbae..428d9726ac2 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -689,6 +689,8 @@ class SystemOneSettingsResponse(BaseModel):
mcp_url: str
# Runtime setting, what a text request to the configured model uses now, and why Auto chose PyTorch.
backend: str = "auto"
+ # Whether "mlx" can be chosen as the runtime on this machine.
+ mlx_available: bool = False
native_ctx: int = 16384
effective_backend: Optional[str] = None
loaded_backend: Optional[str] = None
@@ -1506,6 +1508,17 @@ def update_helper_precache(
return _helper_precache_response(enabled)
+def _decision_description(checkpoint, mlx: bool) -> str:
+ from core.systemone import catalog
+ if (
+ mlx
+ and catalog.MLX_COMPANIONS.get(checkpoint.name)
+ and catalog.CHECKPOINTS.get(checkpoint.name) == checkpoint
+ ):
+ return checkpoint.description.replace("llama.cpp only", "llama.cpp or MLX")
+ return checkpoint.description
+
+
def _clef_availability(checkpoint, reason: Optional[str]) -> dict:
from core.systemone import laya_runtime
@@ -1518,8 +1531,8 @@ def _clef_availability(checkpoint, reason: Optional[str]) -> dict:
return {"llama_cpp_only": True}
if reason is None or getattr(checkpoint, "layout", "laya") != "clef":
return {}
- # llama.cpp serves Clef without CUDA or ROCm.
- if laya_runtime.native_ready(checkpoint):
+ # llama.cpp serves Clef without CUDA or ROCm, and so does the MLX engine on Apple Silicon.
+ if laya_runtime.native_ready(checkpoint) or laya_runtime.mlx_ready(checkpoint):
return {}
return {"available": False, "unavailable_reason": reason}
@@ -1548,7 +1561,10 @@ def _systemone_response(request: Request) -> SystemOneSettingsResponse:
if runtime["error_model"] not in (None, model):
error = None
port = getattr(request.app.state, "server_port", None) or request.scope["server"][1]
+ # First: it waits for device detection, which the MLX answers below read without waiting.
+ gpu_available = systemone_settings.gpu_available()
effective, fallback = laya_runtime.effective_backend(configured)
+ mlx_available = laya_runtime.mlx_available()
if runtime["loaded_model"] == model and runtime["fallback_reason"]:
fallback = runtime["fallback_reason"]
return SystemOneSettingsResponse(
@@ -1556,16 +1572,16 @@ def _systemone_response(request: Request) -> SystemOneSettingsResponse:
enabled_locked = systemone_settings.enabled_locked(),
model = model,
model_locked = systemone_settings.model_locked(),
- # llama.cpp defaults to the GPU when no device is stored; report where it actually runs.
+ # llama.cpp and MLX default to the GPU when no device is stored; report where they actually run.
device = systemone_settings.clef_device()
- if effective == "llama.cpp"
+ if effective in ("llama.cpp", "mlx")
else systemone_settings.get_device(),
device_locked = systemone_settings.device_locked(),
- gpu_available = systemone_settings.gpu_available(),
+ gpu_available = gpu_available,
models = [
SystemOneModelOption(
name = c.name,
- description = c.description,
+ description = _decision_description(c, mlx_available),
download_bytes = c.download_bytes,
label = c.label,
**_clef_availability(c, clef_reason),
@@ -1590,6 +1606,7 @@ def _systemone_response(request: Request) -> SystemOneSettingsResponse:
error = error,
mcp_url = f"http://127.0.0.1:{port}{MCP_PATH}/",
backend = systemone_settings.get_backend(),
+ mlx_available = mlx_available,
native_ctx = systemone_settings.get_native_ctx(),
effective_backend = effective,
loaded_backend = runtime["loaded_backend"] if runtime["loaded_model"] else None,
diff --git a/studio/backend/tests/test_decision_serving.py b/studio/backend/tests/test_decision_serving.py
index e2bcdcb7f28..28d1e525e98 100644
--- a/studio/backend/tests/test_decision_serving.py
+++ b/studio/backend/tests/test_decision_serving.py
@@ -6,7 +6,10 @@ import json
import os
import shutil
import struct
+import sys
+import threading
import time
+from pathlib import Path
from types import SimpleNamespace
import httpx
@@ -24,6 +27,7 @@ from utils.account_context import OWNER, run_as
from utils.paths import outputs_root
_REAL_LOAD = laya_runtime._load_checkpoint
+_REAL_ENGINE = laya_runtime._engine_available
QUESTIONS = {"urgent": {"type": "noul", "instructions": "Does this need a reply now?"}}
UPSTREAM = {
"model": "jev-1.13",
@@ -49,6 +53,8 @@ def home(tmp_path, monkeypatch):
for name in ("_agent", "_loaded", "_device_name", "_loader", "_loading", "_failure"):
monkeypatch.setattr(laya_runtime, name, None)
monkeypatch.setattr(systemone_settings, "runtime_unavailable_reason", lambda: None)
+ # The MLX engine is opted into per test, so a run on Apple Silicon selects what CI does.
+ monkeypatch.setattr(laya_runtime, "_engine_available", lambda: False)
monkeypatch.setattr(
laya_runtime, "_load_checkpoint", lambda checkpoint: (SimpleNamespace(), "cpu")
)
@@ -597,3 +603,283 @@ def test_a_clef_worker_that_died_after_loading_is_a_worker_error():
with pytest.raises(clef_runtime.ClefWorkerError, match = "exited"):
_clef_agent(Conn()).decide("state", {})
+
+
+def engine(home, monkeypatch, tmp_path):
+ _spoof_device(monkeypatch, "mlx")
+ monkeypatch.setattr("utils.hardware.hardware.DETECTION_COMPLETE", done := threading.Event())
+ done.set()
+ state = SimpleNamespace(loaded = [], asked = [], error = None, cached = set())
+
+ def answer(state_, questions):
+ state.asked.append(questions)
+ if state.error:
+ raise state.error("no")
+ answers = {name: {"type": "noul", "noul": 0.5} for name in questions}
+ return {"answers": answers, "usage": {"input_tokens": 3}}
+
+ def load(folder, family, base_model):
+ state.loaded.append((folder.name, family, base_model and base_model.name))
+ tokenizer = SimpleNamespace(encode = lambda text, **_: [0] * len(text.encode()))
+ return SimpleNamespace(answer = answer, tokenizer = tokenizer)
+
+ def dirs(checkpoint, local_only):
+ if local_only and checkpoint.name not in state.cached:
+ raise FileNotFoundError(checkpoint.name)
+ if checkpoint.layout == "clef":
+ return Path(checkpoint.source), None
+ base = catalog.MLX_COMPANIONS[checkpoint.name].base
+ return tmp_path / checkpoint.name, base and tmp_path / base.repo.split("/")[1]
+
+ zoo = SimpleNamespace(load_decision_model = load)
+ zoo.DecisionRequestError = type("RequestError", (ValueError,), {})
+ zoo.DecisionUnsupportedError = type("UnsupportedError", (zoo.DecisionRequestError,), {})
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.decision", zoo)
+ monkeypatch.setattr(laya_runtime, "_engine_available", _REAL_ENGINE)
+ monkeypatch.setattr(laya_runtime, "_load_checkpoint", _REAL_LOAD)
+ monkeypatch.setattr(laya_runtime, "_mlx_dirs", dirs)
+ monkeypatch.setattr(laya_runtime, "_training_active", lambda: False)
+ # Whatever an earlier test in this process left holding the GPU.
+ monkeypatch.setattr("core.inference.gpu_arbiter._owner", None)
+ yield state
+ laya_runtime.unload()
+
+
+def test_apple_silicon_answers_text_through_the_mlx_engine(home, client, engine, monkeypatch):
+ served, folder = _clef_fine_tune(home, "clef_mlx_1"), home / "clef_mlx_1"
+ assert _put(client, enabled = True, model = "kev-4b").status_code == 200
+ answered = _post(client)
+ assert answered.status_code == 200 and answered.json()["answers"]["urgent"]["noul"] == 0.5
+ assert engine.loaded == [("kev-4b", "kev", "Qwen3.5-4B-Base")]
+ settings = client.get("/api/settings/systemone").json()
+ assert (settings["effective_backend"], settings["loaded_backend"]) == ("mlx", "mlx")
+ models = {m["name"]: m for m in settings["models"]}
+ assert all(models[name]["available"] for name in (served, "clef-flash", "kev-4b"))
+ assert _post(client, served).headers["x-unsloth-decision-backend"] == "mlx"
+ assert engine.loaded[-1] == ("clef_mlx_1", "clef", None)
+ # Images, a forced runtime and a Clef saved as adapters are not the engine's.
+ kev = catalog.CHECKPOINTS["kev-4b"]
+ assert laya_runtime._mlx_choice(kev, ["png"], None, "auto") is None
+ assert laya_runtime._mlx_choice(kev, None, None, "llama.cpp") is None
+ (folder / "config.json").rename(folder / "adapter_config.json")
+ (folder / "model.safetensors").rename(folder / "adapter_model.safetensors")
+ assert laya_runtime._mlx_target(catalog.fine_tune(served)) is None
+ # A downloaded GGUF serves before the MLX form is fetched.
+ laya_runtime.unload()
+ monkeypatch.setattr(laya_runtime, "_native_unavailable", lambda *args: None)
+ monkeypatch.setattr(laya_runtime, "is_cached", laya_runtime._is_native)
+ assert laya_runtime.select(kev)[0].backend == "llama.cpp"
+ monkeypatch.setattr(laya_runtime, "is_cached", lambda checkpoint: True)
+ assert laya_runtime.select(kev)[0].backend == "mlx"
+
+
+def test_the_mlx_runtime_serves_only_through_the_engine(home, client, engine, monkeypatch):
+ served, folder = _clef_fine_tune(home, "clef_mlx_2"), home / "clef_mlx_2"
+ kev = catalog.CHECKPOINTS["kev-4b"]
+ assert _put(client, enabled = True, model = "kev-4b", backend = "mlx").status_code == 200
+ settings = client.get("/api/settings/systemone").json()
+ assert settings["mlx_available"] and settings["effective_backend"] == "mlx"
+ described = {m["name"]: "llama.cpp or MLX" in m["description"] for m in settings["models"]}
+ assert described["kev-9b"] and not described["laya-gguf"]
+ assert _post(client, served).headers["x-unsloth-decision-backend"] == "mlx"
+ tuned = catalog.fine_tune(served)
+ # Unlike Auto, a downloaded GGUF does not take the request.
+ monkeypatch.setattr(laya_runtime, "_native_unavailable", lambda *args: None)
+ monkeypatch.setattr(laya_runtime, "is_cached", laya_runtime._is_native)
+ assert laya_runtime.select(kev)[0].backend == "mlx"
+ assert laya_runtime.mlx_ready(kev) and not laya_runtime.native_ready(kev)
+ assert _post(client).headers["x-unsloth-decision-backend"] == "mlx"
+ with pytest.raises(laya_runtime.Unavailable, match = "Images are served only by llama.cpp"):
+ laya_runtime.select(kev, ["png"])
+ (folder / "config.json").rename(folder / "adapter_config.json")
+ (folder / "model.safetensors").rename(folder / "adapter_model.safetensors")
+ with pytest.raises(laya_runtime.Unavailable, match = "has no MLX form"):
+ laya_runtime.select(tuned)
+ assert _put(client, device = "cpu").status_code == 200
+ settings = client.get("/api/settings/systemone").json()
+ assert not settings["mlx_available"] and settings["effective_backend"] is None
+ assert not any("MLX" in m["description"] for m in settings["models"])
+ assert "needs Apple Silicon" in settings["fallback_reason"] and _post(client).status_code == 400
+ plan = client.get("/api/settings/systemone/resolve", params = {"backend": "mlx"}).json()
+ assert (plan["repo"], plan["cached"]) == (None, False) and "needs Apple Silicon" in plan[
+ "error"
+ ]
+ assert _put(client, backend = "mlx-lm").status_code == 400
+
+
+def test_the_mlx_engine_asks_by_id_and_reports_what_it_refuses(home, client, engine):
+ assert _put(client, enabled = True, model = "julia-1").status_code == 200
+ questions = {"urgent": {"type": "noul"}, "late": {"type": "noul", "instructions": "Late?"}}
+ body = {"model": "default", "state": "s", "questions": questions}
+ assert client.post("/v1/systemone", json = body).status_code == 200
+ assert [q["instructions"] for q in engine.asked[0].values()] == ["urgent", "Late?"]
+ zoo = sys.modules["unsloth_zoo.mlx.decision"]
+ for error, status in ((zoo.DecisionRequestError, 422), (zoo.DecisionUnsupportedError, 501)):
+ engine.error = error
+ assert _post(client).status_code == status
+ engine.error, asked = None, len(engine.asked)
+ states = ("w " * 8000, "w " * 8193, "é" * 8193, ["é" * 8000], "s")
+ for state, status in zip(states, (200, 422, 422, 200, 422)):
+ questions["late"]["instructions"] = "w " * 8193 if state == "s" else "Late?"
+ body["state"] = state
+ assert client.post("/v1/systemone", json = body).status_code == status
+ assert len(engine.asked) == asked + 2
+
+
+def test_an_mlx_encoder_refuses_a_state_past_its_window(home, client, engine, tmp_path):
+ encoder = tmp_path / "julia-1" / "encoder"
+ encoder.mkdir(parents = True)
+ (encoder / "config.json").write_text('{"max_position_embeddings": 64}', encoding = "utf-8")
+ assert _put(client, enabled = True, model = "julia-1").status_code == 200
+ body = {"model": "default", "questions": {"urgent": {"type": "noul"}}}
+ # 64 positions less [cls], three [sep] and the question head (0 in this stand-in model).
+ for state, status in (("w" * 60, 200), ("w" * 61, 422)):
+ assert client.post("/v1/systemone", json = {**body, "state": state}).status_code == status
+ assert len(engine.asked) == 1
+
+
+def test_an_mlx_decoder_waits_for_the_gpu(home, client, engine, monkeypatch):
+ from core.inference import gpu_arbiter
+
+ assert _put(client, enabled = True).status_code == 200
+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)
+ assert _post(client, "kev-4b").status_code == 409
+ assert _post(client, "julia-1").status_code == 200
+ assert gpu_arbiter.current_owner() == gpu_arbiter.CHAT
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ assert _post(client, "kev-4b").status_code == 200
+ agent = laya_runtime._agent
+ assert gpu_arbiter.current_owner() == gpu_arbiter.DECISIONS
+ # A chat load ends the idle decoder through the arbiter, and its weights go with it.
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.CHAT, lambda: None)
+ gpu_arbiter.acquire_for(gpu_arbiter.CHAT)
+ assert laya_runtime._agent is None and agent.model is None
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ assert _post(client, "kev-4b").status_code == 200
+ laya_runtime.unload()
+ assert gpu_arbiter.current_owner() is None
+ # A load that loses the GPU to a training run gives its memory back before the claim.
+ freed = []
+ monkeypatch.setattr(laya_runtime, "_release_memory", lambda: freed.append(gpu_arbiter._owner))
+ engine.loaded.clear()
+ monkeypatch.setattr(laya_runtime, "_training_active", lambda: bool(engine.loaded))
+ assert _post(client, "kev-4b").status_code != 200
+ assert freed[-1] == gpu_arbiter.DECISIONS and gpu_arbiter.current_owner() is None
+
+
+def test_the_mlx_engine_needs_apple_silicon_and_the_gpu(home, client, engine, monkeypatch):
+ hardware = sys.modules["utils.hardware.hardware"]
+ kev = catalog.CHECKPOINTS["kev-4b"]
+ assert _put(client, device = "cpu").status_code == 200
+ assert laya_runtime._mlx_target(kev) is None
+ assert _put(client, enabled = True, device = "gpu").status_code == 200
+ assert laya_runtime._mlx_target(kev) is not None
+ # While detection is still running the answer is no: a settings read never waits for it.
+ waited = []
+ hardware.DETECTION_COMPLETE.clear()
+ monkeypatch.setattr(hardware, "get_device", lambda: waited.append(1) or hardware.DeviceType.MLX)
+ assert laya_runtime._mlx_target(kev) is None and not waited
+ hardware.DETECTION_COMPLETE.set()
+ for apple in (False, True):
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: apple)
+ assert _post(client, "kev-4b").status_code == 200 and bool(waited) == apple
+ assert laya_runtime._mlx_target(kev) is not None
+ _spoof_device(monkeypatch, "cuda")
+ assert laya_runtime._mlx_target(kev) is None
+ _spoof_device(monkeypatch, "mlx")
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.decision", None)
+ assert laya_runtime._mlx_target(kev) is None
+
+
+def test_settings_report_mlx_as_detection_settles_and_where_it_runs(
+ home, client, engine, monkeypatch
+):
+ hardware = sys.modules["utils.hardware.hardware"]
+ assert _put(client, enabled = True, model = "kev-4b").status_code == 200
+ # No device stored: MLX takes the GPU, as llama.cpp does, and the response says so.
+ settings = client.get("/api/settings/systemone").json()
+ assert (settings["effective_backend"], settings["device"]) == ("mlx", "gpu")
+ # Detection finishing inside this read's own wait for it is seen by the MLX answers too.
+ hardware.DETECTION_COMPLETE.clear()
+ monkeypatch.setattr(
+ hardware,
+ "get_device",
+ lambda: hardware.DETECTION_COMPLETE.set() or hardware.DeviceType.MLX,
+ )
+ settings = client.get("/api/settings/systemone").json()
+ assert settings["mlx_available"] and settings["effective_backend"] == "mlx"
+
+
+def test_mlx_sources_are_fetched_at_their_pinned_revisions(home, monkeypatch, tmp_path):
+ fetched = []
+
+ def download(repo, revision, allow_patterns, local_files_only, **kwargs):
+ folder = tmp_path / f"{repo.replace('/', '--')}@{revision}"
+ if local_files_only and not folder.is_dir():
+ raise FileNotFoundError(revision)
+ if not local_files_only:
+ fetched.append((repo, revision))
+ for name in allow_patterns:
+ (folder / name).parent.mkdir(parents = True, exist_ok = True)
+ (folder / name).touch()
+ return str(folder)
+
+ monkeypatch.setattr("huggingface_hub.snapshot_download", download)
+ monkeypatch.setattr(laya_runtime, "_engine_available", lambda: True)
+ kev = catalog.MLX_COMPANIONS["kev-4b"]
+ target = laya_runtime._mlx_target(catalog.CHECKPOINTS["kev-4b"])
+ plan = laya_runtime.download_plan(target)
+ assert (plan["repo"], plan["revision"]) == (kev.base.repo, kev.base.revision)
+ assert not plan["cached"] and not fetched
+ laya_runtime._repo_dir(kev.base, False)
+ plan = laya_runtime.download_plan(target)
+ assert plan == {**plan, "repo": kev.repo, "revision": kev.revision, "files": sorted(kev.files)}
+ folder, base = laya_runtime._mlx_dirs(target, local_only = False)
+ assert fetched == [(kev.base.repo, kev.base.revision), (kev.repo, kev.revision)]
+ assert (base / "config.json").is_file() and laya_runtime.is_cached(target)
+ # A settings download holds the repo's main: it serves, without another fetch, where the pinned revision is not complete.
+ (folder / "head.pt").unlink()
+ assert not laya_runtime.is_cached(target)
+ main = Path(download(kev.repo, None, kev.files, False))
+ del fetched[:]
+ assert laya_runtime.is_cached(target)
+ assert laya_runtime._mlx_dirs(target, local_only = False)[0] == main and not fetched
+ (main / "head.pt").unlink()
+ assert not laya_runtime.is_cached(target)
+
+
+def test_images_in_the_state_route_like_the_images_field(home, monkeypatch):
+ seen = []
+
+ def select(
+ checkpoint,
+ images = None,
+ questions = None,
+ preference = None,
+ state_images = False,
+ ):
+ seen.append(state_images and not images)
+ raise laya_runtime.Unavailable(400, "api_usage_error", "stop")
+
+ monkeypatch.setattr(laya_runtime, "select", select)
+ part = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}
+ chat = [{"role": "user", "content": [{"type": "text", "text": "hi"}, part]}]
+ cases = (
+ (chat, True),
+ ({"messages": chat}, True),
+ ([{"role": "user", "content": "hi"}], False),
+ ("s", False),
+ )
+ for state, routed in cases:
+ with pytest.raises(laya_runtime.Unavailable):
+ laya_runtime._route(catalog.CHECKPOINTS["kev-4b"], state, {"q": {"type": "noul"}}, None)
+ assert bool(seen[-1]) == routed
+
+
+def test_auto_keeps_images_in_the_state_off_mlx(home, engine, monkeypatch):
+ kev = catalog.CHECKPOINTS["kev-4b"]
+ monkeypatch.setattr(laya_runtime, "_native_unavailable", lambda *args: None)
+ monkeypatch.setattr(laya_runtime, "is_cached", lambda checkpoint: True)
+ assert laya_runtime.select(kev)[0].backend == "mlx"
+ assert laya_runtime.select(kev, state_images = True)[0].backend == "llama.cpp"
diff --git a/studio/backend/utils/systemone_settings.py b/studio/backend/utils/systemone_settings.py
index 73bf5b3eb92..ddf857c451c 100644
--- a/studio/backend/utils/systemone_settings.py
+++ b/studio/backend/utils/systemone_settings.py
@@ -17,7 +17,7 @@ BACKEND_KEY = "systemone_backend"
NATIVE_CTX_KEY = "systemone_native_ctx"
DEFAULT_MODEL = "laya-multilingual"
DEVICES = ("cpu", "gpu")
-BACKENDS = ("auto", "llama.cpp", "pytorch")
+BACKENDS = ("auto", "llama.cpp", "mlx", "pytorch")
DEFAULT_NATIVE_CTX = 16384
# -c / -b / -ub of the llama.cpp decision server; compute memory grows with it (~0.24 MiB GPU per token).
NATIVE_CTX_RANGE = (512, 65536)
@@ -173,7 +173,7 @@ def validate(
values[DEVICE_KEY] = device
if backend is not None:
if backend not in BACKENDS:
- raise ValueError("Runtime must be auto, llama.cpp or pytorch.")
+ raise ValueError("Runtime must be auto, llama.cpp, mlx or pytorch.")
values[BACKEND_KEY] = backend
if native_ctx is not None:
if not _valid_ctx(native_ctx):
diff --git a/studio/frontend/src/features/settings/api/systemone.ts b/studio/frontend/src/features/settings/api/systemone.ts
index c2c7d51a646..6a5e5fa4fb7 100644
--- a/studio/frontend/src/features/settings/api/systemone.ts
+++ b/studio/frontend/src/features/settings/api/systemone.ts
@@ -9,7 +9,12 @@ import {
import type { DecisionResponse } from "../lib/decision-request";
export type SystemOneDevice = "cpu" | "gpu";
-export type SystemOneBackend = "auto" | "llama.cpp" | "pytorch";
+export type SystemOneBackend = "auto" | "llama.cpp" | "mlx" | "pytorch";
+
+/** The runtime name as the settings page shows it. */
+export function decisionRuntimeLabel(backend: string): string {
+ return backend === "mlx" ? "MLX" : backend;
+}
export type SystemOneModel = {
name: string;
@@ -38,6 +43,7 @@ export type SystemOneSettings = {
error: string | null;
mcpUrl: string;
backend: SystemOneBackend;
+ mlxAvailable: boolean;
nativeCtx: number;
effectiveBackend: string | null;
loadedBackend: string | null;
@@ -116,6 +122,8 @@ type ApiSystemOneSettings = {
mcp_url: string;
backend?: SystemOneBackend;
// biome-ignore lint/style/useNamingConvention: API schema
+ mlx_available?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
native_ctx?: number;
// biome-ignore lint/style/useNamingConvention: API schema
effective_backend?: string | null;
@@ -196,6 +204,7 @@ function fromApi(settings: ApiSystemOneSettings): SystemOneSettings {
error: settings.error,
mcpUrl: settings.mcp_url,
backend: settings.backend ?? "auto",
+ mlxAvailable: settings.mlx_available ?? false,
nativeCtx: settings.native_ctx ?? 16384,
effectiveBackend: settings.effective_backend ?? null,
loadedBackend: settings.loaded_backend ?? null,
diff --git a/studio/frontend/src/features/settings/components/decision-api-section.tsx b/studio/frontend/src/features/settings/components/decision-api-section.tsx
index 11a0328b506..175c0d55c4c 100644
--- a/studio/frontend/src/features/settings/components/decision-api-section.tsx
+++ b/studio/frontend/src/features/settings/components/decision-api-section.tsx
@@ -50,6 +50,7 @@ import { type ReactElement, useEffect, useRef, useState } from "react";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import {
type SystemOneBackend,
+ decisionRuntimeLabel,
type SystemOneConnection,
type SystemOneDevice,
type SystemOneDownloadPlan,
@@ -123,7 +124,8 @@ export function DecisionApiSection(): ReactElement | null {
}, [decisionTryRequested, settings]);
const model = settings?.model ?? null;
const backend = settings?.backend ?? "auto";
- // llama.cpp serves a GGUF, PyTorch the safetensors: the download follows the runtime.
+ const mlxAvailable = settings?.mlxAvailable ?? false;
+ // llama.cpp serves a GGUF, MLX and PyTorch the safetensors: the download follows the runtime.
const plan =
planState?.model === model && planState?.backend === backend
? planState.plan
@@ -192,7 +194,8 @@ export function DecisionApiSection(): ReactElement | null {
return () => {
live = false;
};
- }, [enabled, model, backend, downloadDone]);
+ // MLX coming or going, as on a device change, changes what the runtime serves from.
+ }, [enabled, model, backend, mlxAvailable, downloadDone]);
const modelLabel = (name: string) => {
const connection = connections?.find((c) => c.name === name);
@@ -425,7 +428,7 @@ export function DecisionApiSection(): ReactElement | null {
const remote = connections?.find((c) => c.name === settings.model);
const knownModel = current !== undefined || isRemote;
const longLabel = isRemote || current?.kind === "fine_tune";
- // Laya is PyTorch only; Clef runs on either runtime, a GGUF-only model on llama.cpp only.
+ // Laya is PyTorch only; Clef runs on any runtime, a GGUF-only model on llama.cpp or MLX.
const runtimeChoice =
isClefDecisionModel(settings.model) ||
settings.layout === "clef" ||
@@ -645,7 +648,11 @@ export function DecisionApiSection(): ReactElement | null {
<>
<SettingsRow
label={t("settings.apiKeys.decisionApi.backend")}
- description={t("settings.apiKeys.decisionApi.backendDescription")}
+ description={t(
+ settings.mlxAvailable
+ ? "settings.apiKeys.decisionApi.backendDescriptionMlx"
+ : "settings.apiKeys.decisionApi.backendDescription",
+ )}
>
<Select
value={backend}
@@ -665,6 +672,11 @@ export function DecisionApiSection(): ReactElement | null {
{t("settings.apiKeys.decisionApi.backendAuto")}
</SelectItem>
<SelectItem value="llama.cpp">llama.cpp</SelectItem>
+ {settings.mlxAvailable || backend === "mlx" ? (
+ <SelectItem value="mlx">
+ {decisionRuntimeLabel("mlx")}
+ </SelectItem>
+ ) : null}
<SelectItem value="pytorch">PyTorch</SelectItem>
</SelectContent>
</Select>
@@ -674,11 +686,12 @@ export function DecisionApiSection(): ReactElement | null {
data-decision-backend
>
{t("settings.apiKeys.decisionApi.backendStatus", {
- backend:
+ backend: decisionRuntimeLabel(
(settings.loadedModel === settings.model
? settings.loadedBackend
: settings.effectiveBackend) ??
- t("settings.apiKeys.decisionApi.backendNone"),
+ t("settings.apiKeys.decisionApi.backendNone"),
+ ),
})}
{settings.fallbackReason ? ` · ${settings.fallbackReason}` : ""}{" "}
{t(
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index e8a99849d03..a290044de20 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2816,6 +2816,8 @@ export const ar = {
backendAuto: "تلقائي",
backendDescription:
"يشغّل الوضع التلقائي Clef عبر llama.cpp عندما يتوفر للنموذج إصدار GGUF، ويعود إلى PyTorch في غير ذلك. يقرأ llama.cpp الصور أيضًا.",
+ backendDescriptionMlx:
+ "يشغّل الوضع التلقائي نصوص Clef عبر MLX على Apple Silicon، وعبر llama.cpp عندما يكون إصدار GGUF للنموذج وحده هو المحمّل أو المنزّل. يقرأ MLX النص فقط؛ ويقرأ llama.cpp الصور أيضًا.",
backendStatus: "بيئة التشغيل: {backend}",
backendNone: "غير متاحة",
mediaImages: "يقرأ النصوص والصور.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 36990718b9b..5c8274ff453 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2860,6 +2860,8 @@ export const de = {
backendAuto: "Automatisch",
backendDescription:
"Automatisch stellt Clef über llama.cpp bereit, wenn das Modell einen GGUF-Build hat, und weicht sonst auf PyTorch aus. llama.cpp liest auch Bilder.",
+ backendDescriptionMlx:
+ "Automatisch stellt Clef-Text auf Apple Silicon über MLX bereit und über llama.cpp, wenn nur der GGUF-Build des Modells geladen oder heruntergeladen ist. MLX liest nur Text; llama.cpp liest auch Bilder.",
backendStatus: "Laufzeit: {backend}",
backendNone: "nicht verfügbar",
mediaImages: "Liest Text und Bilder.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index e8f94792eb2..f14ad81fd67 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2888,6 +2888,8 @@ export const en = {
backendAuto: "Auto",
backendDescription:
"Auto serves Clef through llama.cpp when the model has a GGUF build and falls back to PyTorch otherwise. llama.cpp also reads images.",
+ backendDescriptionMlx:
+ "Auto serves Clef text through MLX on Apple Silicon and through llama.cpp when only the model's GGUF build is loaded or downloaded. MLX reads text only. llama.cpp also reads images.",
backendStatus: "Runtime: {backend}",
backendNone: "unavailable",
mediaImages: "Reads text and images.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index df87bc1008d..5d6613c714b 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2853,6 +2853,8 @@ export const es = {
backendAuto: "Automático",
backendDescription:
"Automático sirve Clef mediante llama.cpp cuando el modelo tiene una versión GGUF y recurre a PyTorch en caso contrario. llama.cpp también lee imágenes.",
+ backendDescriptionMlx:
+ "Automático sirve el texto de Clef mediante MLX en Apple Silicon y mediante llama.cpp cuando solo la versión GGUF del modelo está cargada o descargada. MLX solo lee texto; llama.cpp también lee imágenes.",
backendStatus: "Entorno de ejecución: {backend}",
backendNone: "no disponible",
mediaImages: "Lee texto e imágenes.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 853c759e0dc..cfa0bf1d02d 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2861,6 +2861,8 @@ export const fr = {
backendAuto: "Automatique",
backendDescription:
"Automatique sert Clef via llama.cpp lorsque le modèle a une version GGUF, et se rabat sur PyTorch sinon. llama.cpp lit aussi les images.",
+ backendDescriptionMlx:
+ "Automatique sert le texte de Clef via MLX sur Apple Silicon, et via llama.cpp lorsque seule la version GGUF du modèle est chargée ou téléchargée. MLX ne lit que le texte ; llama.cpp lit aussi les images.",
backendStatus: "Moteur d'exécution : {backend}",
backendNone: "indisponible",
mediaImages: "Lit le texte et les images.",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 649e8f27a2b..4b2cd54ca97 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -2927,6 +2927,8 @@ export const he = {
backendAuto: "אוטומטי",
backendDescription:
"במצב אוטומטי Clef מוגש דרך llama.cpp כשלמודל יש גרסת GGUF, ואחרת דרך PyTorch. llama.cpp קורא גם תמונות.",
+ backendDescriptionMlx:
+ "במצב אוטומטי טקסט של Clef מוגש דרך MLX ב-Apple Silicon, ודרך llama.cpp כשרק גרסת ה-GGUF של המודל טעונה או הורדה. MLX קורא טקסט בלבד; llama.cpp קורא גם תמונות.",
backendStatus: "סביבת ריצה: {backend}",
backendNone: "לא זמין",
mediaImages: "קורא טקסט ותמונות.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 9aefa555dd7..69bba7c501e 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2822,6 +2822,8 @@ export const hi = {
backendAuto: "ऑटो",
backendDescription:
"मॉडल का GGUF बिल्ड होने पर ऑटो Clef को llama.cpp से चलाता है, वरना PyTorch पर चला जाता है। llama.cpp इमेज भी पढ़ता है।",
+ backendDescriptionMlx:
+ "Apple Silicon पर ऑटो Clef का टेक्स्ट MLX से चलाता है, और केवल मॉडल का GGUF बिल्ड लोड या डाउनलोड होने पर llama.cpp से। MLX केवल टेक्स्ट पढ़ता है; llama.cpp इमेज भी पढ़ता है।",
backendStatus: "रनटाइम: {backend}",
backendNone: "उपलब्ध नहीं",
mediaImages: "टेक्स्ट और इमेज पढ़ता है।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 6176145dfd8..f31ea39c2f7 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2819,6 +2819,8 @@ export const it = {
backendAuto: "Automatico",
backendDescription:
"Automatico serve Clef tramite llama.cpp quando il modello ha una build GGUF, altrimenti ripiega su PyTorch. llama.cpp legge anche le immagini.",
+ backendDescriptionMlx:
+ "Automatico serve il testo di Clef tramite MLX su Apple Silicon e tramite llama.cpp quando solo la build GGUF del modello è caricata o scaricata. MLX legge solo testo; llama.cpp legge anche le immagini.",
backendStatus: "Runtime: {backend}",
backendNone: "non disponibile",
mediaImages: "Legge testo e immagini.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index f03d6d8f350..cdca1d3a0d4 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2786,6 +2786,8 @@ export const ja = {
backendAuto: "自動",
backendDescription:
"自動では、モデルに GGUF ビルドがあれば Clef を llama.cpp で提供し、なければ PyTorch に切り替えます。llama.cpp は画像も読み取れます。",
+ backendDescriptionMlx:
+ "自動では、Apple Silicon 上で Clef のテキストを MLX で提供し、モデルの GGUF ビルドだけが読み込み済みまたはダウンロード済みの場合は llama.cpp で提供します。MLX はテキストのみを読み取り、llama.cpp は画像も読み取れます。",
backendStatus: "ランタイム: {backend}",
backendNone: "利用不可",
mediaImages: "テキストと画像を読み取ります。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 43b38fa6b18..63d4703564c 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2806,6 +2806,8 @@ export const ko = {
backendAuto: "자동",
backendDescription:
"자동은 모델에 GGUF 빌드가 있으면 llama.cpp로 Clef를 제공하고, 없으면 PyTorch로 대체합니다. llama.cpp는 이미지도 읽습니다.",
+ backendDescriptionMlx:
+ "자동은 Apple Silicon에서 Clef 텍스트를 MLX로 제공하고, 모델의 GGUF 빌드만 로드되었거나 다운로드된 경우 llama.cpp로 제공합니다. MLX는 텍스트만 읽고, llama.cpp는 이미지도 읽습니다.",
backendStatus: "런타임: {backend}",
backendNone: "사용할 수 없음",
mediaImages: "텍스트와 이미지를 읽습니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4fdde473fc8..077cea05f07 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2832,6 +2832,8 @@ export const ptBR = {
backendAuto: "Automático",
backendDescription:
"O automático serve o Clef pelo llama.cpp quando o modelo tem uma versão GGUF e recorre ao PyTorch caso contrário. O llama.cpp também lê imagens.",
+ backendDescriptionMlx:
+ "O automático serve o texto do Clef pelo MLX no Apple Silicon e pelo llama.cpp quando apenas a versão GGUF do modelo está carregada ou baixada. O MLX lê apenas texto; o llama.cpp também lê imagens.",
backendStatus: "Runtime: {backend}",
backendNone: "indisponível",
mediaImages: "Lê texto e imagens.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 05f1f741c25..e570de4b2f3 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2827,6 +2827,8 @@ export const ru = {
backendAuto: "Авто",
backendDescription:
"В режиме «Авто» Clef работает через llama.cpp, если у модели есть сборка GGUF, а иначе через PyTorch. llama.cpp также читает изображения.",
+ backendDescriptionMlx:
+ "В режиме «Авто» текст Clef на Apple Silicon обрабатывается через MLX, а через llama.cpp — если загружена или скачана только сборка GGUF модели. MLX читает только текст; llama.cpp также читает изображения.",
backendStatus: "Среда выполнения: {backend}",
backendNone: "недоступна",
mediaImages: "Читает текст и изображения.",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 47461269b7a..8555383dd47 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -3027,6 +3027,8 @@ export const sv = {
backendAuto: "Automatisk",
backendDescription:
"Automatisk kör Clef via llama.cpp när modellen har en GGUF-version och faller annars tillbaka på PyTorch. llama.cpp läser också bilder.",
+ backendDescriptionMlx:
+ "Automatisk kör Clef-text via MLX på Apple Silicon och via llama.cpp när bara modellens GGUF-version är laddad eller nedladdad. MLX läser bara text; llama.cpp läser också bilder.",
backendStatus: "Körmiljö: {backend}",
backendNone: "inte tillgänglig",
mediaImages: "Läser text och bilder.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 5d2a9b42594..1407cf90042 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2765,6 +2765,8 @@ export const zhCN = {
backendAuto: "自动",
backendDescription:
"自动模式下,模型有 GGUF 版本时通过 llama.cpp 提供 Clef,否则回退到 PyTorch。llama.cpp 还能读取图片。",
+ backendDescriptionMlx:
+ "自动模式下,在 Apple Silicon 上通过 MLX 提供 Clef 文本;仅模型的 GGUF 版本已加载或已下载时通过 llama.cpp 提供。MLX 仅读取文本;llama.cpp 还能读取图片。",
backendStatus: "运行时:{backend}",
backendNone: "不可用",
mediaImages: "可读取文本和图片。",
diff --git a/studio/frontend/tests/decision-api-section.test.ts b/studio/frontend/tests/decision-api-section.test.ts
index a27342dee85..c1d93748122 100644
--- a/studio/frontend/tests/decision-api-section.test.ts
+++ b/studio/frontend/tests/decision-api-section.test.ts
@@ -100,7 +100,7 @@ test("the download goes through the manager with the exact files and one scope",
/acceptedState === "running" \|\| acceptedState === "complete"/,
);
assert.match(SECTION, /resolveSystemOneDownload\(model, backend\)\.then/);
- assert.match(SECTION, /\[enabled, model, backend, downloadDone\]/);
+ assert.match(SECTION, /\[enabled, model, backend, mlxAvailable, downloadDone\]/);
assert.match(SECTION, /await resyncSettingsAfterError/);
});
@@ -126,6 +126,15 @@ test("GPU is offered only where the backend found one", () => {
);
});
+test("MLX is a runtime only where the backend can serve it", () => {
+ assert.match(
+ SECTION,
+ /\{settings\.mlxAvailable \|\| backend === "mlx" \? \(\s*<SelectItem value="mlx">/,
+ );
+ assert.match(SECTION, /backend: decisionRuntimeLabel\(/);
+ assert.match(API, /return backend === "mlx" \? "MLX" : backend;/);
+});
+
test("the copy stays plain", () => {
const copy = en.settings.apiKeys.decisionApi;
assert.equal("experimental" in copy, false);