Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add chat on the AMD Ryzen AI NPU through Lemonade and FastFlowLM (#11743)
oobaboogafd6f72f7695c
diff --git a/pyproject.toml b/pyproject.tomlindex 075a2366cdd..aef512b1261 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -55,6 +55,7 @@ studio = ["*.ps1","*.bat","node_prebuilt_pins.json",+ "lemonade_prebuilt_pins.json","src-tauri/icons/icon.icns","src-tauri/icons/icon.png","frontend/dist/**/*",diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 9a5c3cdd706..ea27e328290 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -35,7 +35,7 @@ from core.inference.sse_control_frames import sanitize_provider_sse_line# templated just like an in-process one (#7066). "custom" is a user-supplied OpenAI-compatible base_url, i.e. how a# self-hosted vLLM or llama.cpp registers without its preset. Unknown endpoint means assume a template applies:# sweeping a hosted API costs a space in delimiter-like text, not sweeping a local one costs a forged turn.-_TEMPLATE_APPLYING_PROVIDERS = frozenset({"vllm", "llama_cpp", "ollama", "custom"})+_TEMPLATE_APPLYING_PROVIDERS = frozenset({"vllm", "llama_cpp", "ollama", "custom", "lemonade"})# The subset documenting "continue_final_message" + "add_generation_prompt" on /v1/chat/completions._CONTINUATION_FLAG_PROVIDERS = frozenset({"vllm", "llama_cpp"})@@ -44,7 +44,7 @@ _CONTINUATION_FLAG_PROVIDERS = frozenset({"vllm", "llama_cpp"})# providers report no llama.cpp timings either, so the monitor has no token count to derive a speed from. Same caution# as the flag above: "custom" is any user-supplied base_url and a strict endpoint 400s on an unknown field. "openai"# is absent because it routes to /v1/responses, which reports usage on its own.-_USAGE_STREAM_OPTION_PROVIDERS = frozenset({"vllm", "openrouter", "kimi"})+_USAGE_STREAM_OPTION_PROVIDERS = frozenset({"vllm", "openrouter", "kimi", "lemonade"})# llama-server reads repeat_penalty, not repetition_penalty (as routes/inference does)._REPETITION_PENALTY_BODY_KEY = {"llama_cpp": "repeat_penalty"}@@ -884,6 +884,8 @@ def _create_shared_http_client() -> httpx.AsyncClient:_http_client = _create_shared_http_client()+# Studio's own loopback runtime: an env proxy would receive its key and prompts, or fail to reach it.+_loopback_http_client = httpx.AsyncClient(trust_env = False)class _PinnedPublicTransport(httpx.AsyncBaseTransport):@@ -1359,15 +1361,16 @@ class ExternalProviderClient:timeout: float = 120.0,*,api_type: str = "chat_completions",+ managed_loopback: bool = False,):self.provider_type = provider_typeself.api_type = api_type if provider_type == "custom" else "chat_completions"- # Single choke point for every outbound provider request (chat, models, responses, messages, containers): the- # URL is caller-controlled, so it is validated here even when a route already checked it. Routes turn the- # ValueError into a 400; reaching it here means a caller bypassed them.from core.inference.providers import validate_provider_base_url- self.base_url = validate_provider_base_url(base_url)+ self.base_url = (+ base_url.rstrip("/") if managed_loopback else validate_provider_base_url(base_url)+ )+ self._managed_loopback = managed_loopback# Strip a legacy `/openai` suffix from Google-hosted bases so configs saved before the native switch still# route correctly. Custom proxy paths ending in `/openai` are left untouched.if self.provider_type == "gemini":@@ -1674,6 +1677,8 @@ class ExternalProviderClient:body["reasoning_effort"] = effortelif self.provider_type == "ollama":_apply_ollama_reasoning_controls(body, enable_thinking, reasoning_effort)+ elif self.provider_type == "lemonade":+ _apply_fastflowlm_reasoning_controls(body, enable_thinking, reasoning_effort)# OpenRouter's unified `reasoning` field gates per-model thinking. Some routes# (`*_MANDATORY_REASONING_MODELS`) 400 on explicit off.@@ -1733,7 +1738,9 @@ class ExternalProviderClient:)try:- async with _client().stream(+ async with (+ _loopback_http_client if getattr(self, "_managed_loopback", False) else _client()+ ).stream("POST",url,json = body,@@ -1912,6 +1919,8 @@ class ExternalProviderClient:continuefor ann in envelope.get("annotations") or []:_record_or_url_citation(ann)+ if self.provider_type == "lemonade" and line.startswith("{"):+ line = _bare_json_error_as_sse(line) or line# Verbatim relay, minus Unsloth's own UI control protocol: the frames this server writes to# paint tool cards ride the same stream, so an endpoint that echoes them forges a card for a# tool that never ran.@@ -7129,6 +7138,36 @@ _ANTHROPIC_ERROR_STATUS = {}+def _apply_fastflowlm_reasoning_controls(+ body: dict[str, Any], enable_thinking: Optional[bool], reasoning_effort: Optional[str]+) -> None:+ """Translate reasoning controls to FastFlowLM's ``think`` field.++ Explicit thinking preserves reasoning on length cutoffs; effort ``none`` disables it.+ """+ effort = (reasoning_effort or "").strip().lower()+ if effort == "none":+ body["think"] = False+ return+ if enable_thinking is not None:+ body["think"] = bool(enable_thinking)+ if effort in ("low", "medium", "high") and body.get("think", True):+ body["reasoning_effort"] = effort+++def _bare_json_error_as_sse(line: str) -> Optional[str]:+ try:+ parsed = _json.loads(line)+ except ValueError:+ return None+ if not isinstance(parsed, dict) or "error" not in parsed:+ return None+ error = parsed["error"]+ if not isinstance(error, dict):+ error = {"message": str(error), "type": "provider_error"}+ return "data: " + _json.dumps({"error": error})++def _error_sse_line(status_code: int,message: str,diff --git a/studio/backend/core/inference/lemonade_server.py b/studio/backend/core/inference/lemonade_server.pynew file mode 100644index 00000000000..a74870f580f--- /dev/null+++ b/studio/backend/core/inference/lemonade_server.py@@ -0,0 +1,302 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Private Lemonade process serving FastFlowLM on the AMD NPU.++Uses authenticated loopback and owns the child process tree. Runtime, config and models+stay under Studio's home; a separate FLM_MODEL_PATH prevents other FastFlowLM installs+from deleting these models (lemonade-sdk/lemonade#3375). No torch or transformers imports.+"""++from __future__ import annotations++import json+import logging+import secrets+import socket+import subprocess+import threading+import time+from collections import deque+from pathlib import Path+from typing import Any, Optional++import httpx++from utils.native_path_leases import child_env_without_native_path_secret+from utils.process_lifetime import (+ adopt_pid,+ child_popen_kwargs,+ is_process_shutting_down,+ spawn_on_lifetime_thread,+ terminate_pid,+)+from utils.subprocess_compat import windows_hidden_subprocess_kwargs++logger = logging.getLogger(__name__)++_TRANSPORT_ERRORS = (+ httpx.ConnectError,+ httpx.ReadError,+ httpx.RemoteProtocolError,+ httpx.WriteError,+)++_CONFIG_OVERRIDES: dict[str, Any] = {+ "broadcast": False,+ "auto_check_model_updates": False,+ "auto_update_models": False,+ "log_file": "disabled",+ "host": "127.0.0.1",+ "max_loaded_models": 1,+}+++class LemonadeUnavailable(RuntimeError):+ """lemond is not running or stopped answering."""+++def _kill_with_the_parent() -> None:+ """Override the Linux parent-death signal with SIGKILL.++ With a loaded model, SIGTERM held the NPU for about 9 s; SIGKILL released it within 1 s.+ """+ import ctypes+ import signal++ ctypes.CDLL("libc.so.6", use_errno = True).prctl(1, signal.SIGKILL)+++class LemonadeServer:+ def __init__(+ self, binary: Path, *, cache_dir: Path, config_dir: Path, flm_model_dir: Path+ ) -> None:+ self.binary = Path(binary)+ self.cache_dir = Path(cache_dir)+ self.config_dir = Path(config_dir)+ self.flm_model_dir = Path(flm_model_dir)+ self.port: Optional[int] = None+ self.api_key: Optional[str] = None+ self._process: Optional[subprocess.Popen] = None+ self._tail: deque[str] = deque(maxlen = 200)+ self._drain_thread: Optional[threading.Thread] = None+ self._lock = threading.Lock()+ # stop() sets it without the lock, which start() holds while waiting for readiness.+ self._stop_requested = threading.Event()+ self._client = httpx.Client(timeout = 30.0, trust_env = False)++ @property+ def base_url(self) -> str:+ return f"http://127.0.0.1:{self.port}"++ @property+ def pid(self) -> Optional[int]:+ return self._process.pid if self._process is not None else None++ def is_alive(self) -> bool:+ return self._process is not None and self._process.poll() is None++ def log_tail(self, lines: int = 30) -> str:+ return "\n".join(list(self._tail)[-lines:])++ def headers(self) -> dict[str, str]:+ return {"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}++ @staticmethod+ def _find_free_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(("127.0.0.1", 0))+ return int(s.getsockname()[1])++ def _write_config(self) -> None:+ self.config_dir.mkdir(parents = True, exist_ok = True)+ path = self.config_dir / "config.json"+ try:+ config = json.loads(path.read_text(encoding = "utf-8"))+ if not isinstance(config, dict):+ config = {}+ except (OSError, ValueError):+ config = {}+ config.update(_CONFIG_OVERRIDES)+ config["models_dir"] = str(self.cache_dir / "models")+ config.setdefault("flm", {})["prefer_system"] = False+ tmp = path.with_suffix(".json.tmp")+ tmp.write_text(json.dumps(config, indent = 2) + "\n", encoding = "utf-8")+ tmp.replace(path)++ def start(self, timeout: float = 60.0) -> None:+ """Start lemond and wait for authenticated /v1/health to confirm readiness and ownership."""+ with self._lock:+ if self.is_alive():+ return+ self._stop_requested.clear()+ if is_process_shutting_down():+ raise LemonadeUnavailable("Unsloth is shutting down; not starting Lemonade.")+ self.cache_dir.mkdir(parents = True, exist_ok = True)+ self.flm_model_dir.mkdir(parents = True, exist_ok = True)+ self._write_config()+ port = self._find_free_port()+ api_key = secrets.token_urlsafe(32)+ env = child_env_without_native_path_secret()+ env["LEMONADE_API_KEY"] = api_key+ env["FLM_MODEL_PATH"] = str(self.flm_model_dir)+ env["FLM_DISABLE_UPDATE_CHECK"] = "1"+ cmd = [+ str(self.binary),+ str(self.cache_dir),+ str(self.config_dir),+ "--port",+ str(port),+ "--host",+ "127.0.0.1",+ "--no-broadcast",+ "--log-file",+ "disabled",+ ]+ logger.info("Starting Lemonade: %s", " ".join(cmd))+ self._tail.clear()++ def _spawn() -> subprocess.Popen:+ return subprocess.Popen(+ cmd,+ cwd = str(self.binary.parent),+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ stdin = subprocess.DEVNULL,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ env = env,+ **windows_hidden_subprocess_kwargs(),+ **child_popen_kwargs(_kill_with_the_parent),+ )++ proc = spawn_on_lifetime_thread(_spawn)+ adopt_pid(proc.pid)+ self._process = proc+ self.port = port+ self.api_key = api_key+ # Shutdown may have swept children before this process was adopted.+ if is_process_shutting_down():+ self._kill_locked()+ raise LemonadeUnavailable("Unsloth is shutting down; not starting Lemonade.")+ self._drain_thread = threading.Thread(+ target = self._drain, args = (proc,), daemon = True, name = "lemond-drain"+ )+ self._drain_thread.start()+ if not self._wait_ready(timeout):+ # After the kill, which joins the drain thread, so the tail has the last lines.+ self._kill_locked()+ tail = self.log_tail()+ raise LemonadeUnavailable(f"Lemonade did not start. Last output:\n{tail}")++ def _drain(self, proc: subprocess.Popen) -> None:+ try:+ assert proc.stdout is not None+ for raw in proc.stdout:+ line = raw.rstrip()+ if line:+ self._tail.append(line)+ logger.debug("[lemond] %s", line)+ except Exception: # noqa: BLE001 -- the pipe closes at teardown+ pass++ def _wait_ready(self, timeout: float) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if not self.is_alive() or self._stop_requested.is_set():+ return False+ try:+ response = self._client.get(+ f"{self.base_url}/v1/health", headers = self.headers(), timeout = 2.0+ )+ if response.status_code == 200:+ return True+ except (*_TRANSPORT_ERRORS, httpx.TimeoutException):+ pass+ time.sleep(0.25)+ return False++ def request(+ self,+ method: str,+ path: str,+ *,+ json_body: Optional[dict] = None,+ timeout: float = 60.0,+ ) -> httpx.Response:+ if not self.is_alive():+ raise LemonadeUnavailable("Lemonade is not running.")+ try:+ return self._client.request(+ method,+ f"{self.base_url}{path}",+ json = json_body,+ headers = self.headers(),+ timeout = timeout,+ )+ except (*_TRANSPORT_ERRORS, httpx.TimeoutException) as exc:+ detail = (+ "" if self.is_alive() else f" (process exited). Last output:\n{self.log_tail()}"+ )+ raise LemonadeUnavailable(f"Lemonade request {path} failed: {exc}{detail}") from exc++ def stream(+ self,+ method: str,+ path: str,+ *,+ json_body: dict,+ timeout: float = 3600.0,+ ):+ """``httpx.Client.stream`` against lemond, for server-sent progress."""+ if not self.is_alive():+ raise LemonadeUnavailable("Lemonade is not running.")+ return self._client.stream(+ method,+ f"{self.base_url}{path}",+ json = json_body,+ headers = self.headers(),+ timeout = httpx.Timeout(timeout, connect = 10.0, read = timeout),+ )++ def stop(self) -> None:+ """Unload, then stop lemond and every process under it. Idempotent."""+ self._stop_requested.set()+ with self._lock:+ if self.is_alive():+ try:+ self._client.post(+ f"{self.base_url}/v1/unload",+ json = {},+ headers = self.headers(),+ timeout = 10.0,+ )+ except Exception: # noqa: BLE001 -- the kill below still runs+ pass+ self._kill_locked()++ def _kill_locked(self) -> None:+ proc = self._process+ if proc is None:+ return+ try:+ # Kill descendants too: flm.exe survives its parent on Windows.+ terminate_pid(proc.pid, timeout = 10.0, owner_verified = True)+ proc.wait(timeout = 10)+ except Exception as exc: # noqa: BLE001 -- best-effort teardown+ logger.warning("Error stopping Lemonade: %s", exc)+ finally:+ self._process = None+ self.port = None+ self.api_key = None+ if self._drain_thread is not None:+ self._drain_thread.join(timeout = 2)+ self._drain_thread = None++ def close(self) -> None:+ self.stop()+ try:+ self._client.close()+ except Exception: # noqa: BLE001+ passdiff --git a/studio/backend/core/inference/npu_backend.py b/studio/backend/core/inference/npu_backend.pynew file mode 100644index 00000000000..3f414f554a7--- /dev/null+++ b/studio/backend/core/inference/npu_backend.py@@ -0,0 +1,711 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Manage FastFlowLM NPU models through a private Lemonade server.++Installs and validates the runtime, manages its catalog, and loads models by+``lemonade:<id>``. Health checks confirm residency and context length.+GGUF models are unsupported. This module does not import the GPU stack.+"""++from __future__ import annotations++import json+import logging+import subprocess+import sys+import threading+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Iterator, Optional++from core.inference.lemonade_server import LemonadeServer, LemonadeUnavailable+from utils.hardware.npu import detect_amd_npu+from utils.native_path_leases import child_env_without_native_path_secret+from utils.process_lifetime import (+ adopt_pid,+ child_popen_kwargs,+ forget_pid,+ is_process_shutting_down,+ spawn_on_lifetime_thread,+ terminate_pid,+)+from utils.subprocess_compat import windows_hidden_subprocess_kwargs++logger = logging.getLogger(__name__)++MODEL_PREFIX = "lemonade:"+PROVIDER_TYPE = "lemonade"+DEFAULT_CONTEXT_LENGTH = 8192+# Names the lemond install whose NPU passed `flm validate`, so a restart needs no new Enable.+_VALIDATED_MARKER = "npu_validated.json"++# Model modes Unsloth's chat cannot serve: embeddings and transcription have no chat endpoint,+# and a single-turn ("flash") model answers only the first message of a conversation.+_EXCLUDED_LABELS = frozenset({"embeddings", "transcription", "single-turn"})++_VALIDATE_PROBLEMS = (+ ("amd_device_found", "No AMD XDNA 2 NPU was found."),+ ("npu_driver_ok", "The AMD NPU driver is missing or too old."),+ ("all_fw_ok", "The NPU firmware is too old; update linux-firmware or the AMD NPU driver."),+ ("kernel_ok", "This Linux kernel has no amdxdna support; use kernel 7.0+ or amdxdna-dkms."),+ (+ "memlock_ok",+ "The locked-memory limit is too low. Set memlock to unlimited in "+ "/etc/security/limits.conf, then log out and back in.",+ ),+)+DRIVER_HELP_URL = {+ "linux": "https://lemonade-server.ai/flm_npu_linux.html",+ "win32": "https://lemonade-server.ai/driver_install.html",+}+++class NpuError(RuntimeError):+ """An NPU operation failed; the message is safe to show the user."""+++class NpuLoadCancelled(NpuError):+ """A load was stopped by cancel_load."""+++@dataclass(frozen = True)+class NpuModel:+ id: str+ checkpoint: str+ size_gb: Optional[float]+ downloaded: bool+ labels: tuple[str, ...]+ max_context_length: Optional[int]++ @property+ def vision(self) -> bool:+ return "vision" in self.labels++ @property+ def reasoning(self) -> bool:+ return "reasoning" in self.labels++ @property+ def tools(self) -> bool:+ return "tool-calling" in self.labels++ @property+ def model_path(self) -> str:+ return MODEL_PREFIX + self.id++ def to_json(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "model_path": self.model_path,+ "checkpoint": self.checkpoint,+ "size_gb": self.size_gb,+ "downloaded": self.downloaded,+ "labels": list(self.labels),+ "supports_vision": self.vision,+ "supports_reasoning": self.reasoning,+ "supports_tools": self.tools,+ "max_context_length": self.max_context_length,+ }+++@dataclass(frozen = True)+class ManagedUpstream:+ """Server-owned routing and credentials for the loaded NPU model."""++ provider_type: str+ base_url: str+ api_key: str+ model: str+ public_model: str+ supports_vision: bool+ supports_tools: bool+ supports_reasoning: bool+ context_length: Optional[int]+++@dataclass+class _Loaded:+ model: NpuModel+ context_length: Optional[int]+ requested_context_length: Optional[int]+++@dataclass(frozen = True)+class NpuResident:+ """One consistent read of the loaded model, taken without the lock long operations hold."""++ model: NpuModel+ context_length: Optional[int]+ requested_context_length: Optional[int]+ base_url: str+ api_key: str+++def is_npu_model_path(model_path: Optional[str]) -> bool:+ return isinstance(model_path, str) and model_path.startswith(MODEL_PREFIX)+++def model_id_from_path(model_path: str) -> str:+ model_id = model_path[len(MODEL_PREFIX) :].strip()+ if not model_id or "/" in model_id or "\\" in model_id:+ raise NpuError(f"Invalid NPU model id: {model_path!r}")+ return model_id+++def _installer_module():+ studio_dir = Path(__file__).resolve().parents[3]+ if str(studio_dir) not in sys.path:+ sys.path.insert(0, str(studio_dir))+ import install_lemonade_prebuilt++ return install_lemonade_prebuilt+++def _npu_root() -> Path:+ from utils.paths.storage_roots import studio_root+ return studio_root() / "lemonade"+++def _error_message(response) -> str:+ try:+ body = response.json()+ except ValueError:+ return response.text[:500] or f"HTTP {response.status_code}"+ if isinstance(body, dict):+ error = body.get("error")+ if isinstance(error, dict) and error.get("message"):+ return str(error["message"])+ if isinstance(error, str):+ return error+ if body.get("message"):+ return str(body["message"])+ return json.dumps(body)[:500]+++def _failed(response) -> bool:+ """Whether lemond refused, including its 200 answers that carry an error body."""+ if response.status_code != 200:+ return True+ try:+ body = response.json()+ except ValueError:+ return False+ return isinstance(body, dict) and ("error" in body or body.get("status") == "error")+++def _kill_tree(process: subprocess.Popen) -> None:+ # The whole tree: a child's children hold the pipes communicate() waits on.+ terminate_pid(process.pid, timeout = 5.0, owner_verified = True)+++def _positive_int(value: Any) -> Optional[int]:+ try:+ number = int(value)+ except (TypeError, ValueError):+ return None+ return number if number > 0 else None+++class LemonadeNpuBackend:+ def __init__(self, root: Optional[Path] = None) -> None:+ self._root = Path(root) if root is not None else None+ self._lock = threading.RLock()+ self._server: Optional[LemonadeServer] = None+ self._loaded: Optional[_Loaded] = None+ self._loading: Optional[str] = None+ self._load_cancelled = threading.Event()+ # Makes cancel_load and a load's commit exclusive, so a cancel either wins or finds nothing.+ self._commit_lock = threading.Lock()+ self._closing = threading.Event()+ self._validate_process: Optional[subprocess.Popen] = None+ self._hardware: Optional[dict[str, Any]] = None+ self._validation: Optional[dict[str, Any]] = None+ self._state = "idle"+ self._error: Optional[str] = None++ @property+ def root(self) -> Path:+ return self._root if self._root is not None else _npu_root()++ def _installed_lemond(self) -> Optional[Path]:+ try:+ return _installer_module().installed_lemond(self.root)+ except Exception as exc: # noqa: BLE001 -- a broken pin file reads as "not installed"+ logger.warning("Could not read the Lemonade install: %s", exc)+ return None++ def _flm_binary(self) -> Optional[Path]:+ name = "flm.exe" if sys.platform == "win32" else "flm"+ base = self.root / "cache" / "bin" / "flm" / "npu"+ candidates = sorted(base.rglob(name)) if base.is_dir() else []+ return candidates[0] if candidates else None++ def hardware(self) -> dict[str, Any]:+ if self._hardware is None:+ self._hardware = detect_amd_npu()+ return self._hardware++ @property+ def is_loaded(self) -> bool:+ return self.resident() is not None++ @property+ def loaded_model(self) -> Optional[NpuModel]:+ resident = self.resident()+ return resident.model if resident is not None else None++ @property+ def loaded_context_length(self) -> Optional[int]:+ resident = self.resident()+ return resident.context_length if resident is not None else None++ def resident(self) -> Optional[NpuResident]:+ """The loaded model, or None: one snapshot, since unload clears it concurrently."""+ loaded, server = self._loaded, self._server+ if loaded is None or server is None:+ return None+ port, api_key = server.port, server.api_key+ if port is None or not server.is_alive():+ return None+ return NpuResident(+ model = loaded.model,+ context_length = loaded.context_length,+ requested_context_length = loaded.requested_context_length,+ base_url = f"http://127.0.0.1:{port}",+ api_key = api_key or "",+ )++ @property+ def loading_model(self) -> Optional[str]:+ return self._loading++ def _validated_install(self) -> Optional[str]:+ try:+ marker = json.loads((self.root / _VALIDATED_MARKER).read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ return None+ return marker.get("lemond") if isinstance(marker, dict) else None++ def status(self) -> dict[str, Any]:+ hardware = self.hardware()+ binary = self._installed_lemond()+ installed = binary is not None+ ready = self._state == "ready" or (+ self._state == "idle" and installed and self._validated_install() == str(binary)+ )+ running = self._server is not None and self._server.is_alive()+ resident = self.resident()+ platform_key = "linux" if sys.platform.startswith("linux") else sys.platform+ return {+ "supported": bool(hardware.get("supported")),+ "hardware": hardware,+ "runtime_installed": installed,+ "runtime_running": running,+ "state": self._state,+ "ready": ready,+ "error": self._error,+ "validation": self._validation,+ "help_url": DRIVER_HELP_URL.get(platform_key),+ "loaded_model": resident.model.model_path if resident else None,+ "context_length": resident.context_length if resident else None,+ "loading_model": self._loading,+ }++ def _server_for(self, binary: Path) -> LemonadeServer:+ return LemonadeServer(+ binary,+ cache_dir = self.root / "cache",+ config_dir = self.root / "config",+ flm_model_dir = self.root / "flm",+ )++ def _require_supported(self) -> None:+ hardware = self.hardware()+ if not hardware.get("present"):+ raise NpuError("No AMD Ryzen AI NPU was found on this machine.")+ if not hardware.get("supported"):+ raise NpuError(+ "FastFlowLM needs an XDNA 2 NPU (Ryzen AI 300/400 or Ryzen AI Max); "+ "this NPU is XDNA 1."+ )++ def _ensure_running(self) -> LemonadeServer:+ """Start the installed runtime if needed and return its server."""+ with self._lock:+ if self._server is not None and self._server.is_alive():+ return self._server+ binary = self._installed_lemond()+ if binary is None:+ raise NpuError("The NPU runtime is not installed. Enable it first.")+ if self._server is not None:+ self._server.close()+ self._loaded = None+ self._server = self._server_for(binary)+ try:+ self._server.start()+ except LemonadeUnavailable as exc:+ self._server = None+ raise NpuError(str(exc)) from exc+ return self._server++ def enable(self) -> dict[str, Any]:+ """Install Lemonade and FastFlowLM, start them and validate the NPU. Idempotent."""+ self._require_supported()+ with self._lock:+ self._error = None+ (self.root / _VALIDATED_MARKER).unlink(missing_ok = True)+ try:+ self._state = "installing"+ binary = _installer_module().install(self.root, cancel = self._closing)+ self._state = "starting"+ server = self._ensure_running()+ self._state = "installing_flm"+ response = server.request(+ "POST",+ "/v1/install",+ json_body = {"recipe": "flm", "backend": "npu", "stream": False},+ timeout = 900.0,+ )+ if _failed(response):+ raise NpuError(f"Installing FastFlowLM failed: {_error_message(response)}")+ self._state = "validating"+ self._validation = self._validate()+ if not self._validation.get("ready"):+ raise NpuError(+ " ".join(self._validation.get("problems") or ["NPU validation failed."])+ )+ marker = self.root / _VALIDATED_MARKER+ tmp = marker.with_suffix(".json.tmp")+ tmp.write_text(json.dumps({"lemond": str(binary)}) + "\n", encoding = "utf-8")+ tmp.replace(marker)+ self._state = "ready"+ except NpuError as exc:+ self._state = "failed"+ self._error = str(exc)+ raise+ except Exception as exc: # noqa: BLE001 -- surfaced to the user, not swallowed+ self._state = "failed"+ self._error = f"Enabling the NPU runtime failed: {exc}"+ raise NpuError(self._error) from exc+ return self.status()++ def _validate(self) -> dict[str, Any]:+ binary = self._flm_binary()+ if binary is None:+ return {"ready": False, "problems": ["FastFlowLM was not found after installing it."]}+ env = child_env_without_native_path_secret()+ env["FLM_MODEL_PATH"] = str(self.root / "flm")+ env["FLM_DISABLE_UPDATE_CHECK"] = "1"+ if self._closing.is_set():+ return {"ready": False, "problems": ["Unsloth is shutting down."]}+ try:+ # On the lifetime thread: shutdown() kills it, and it dies with a crashed Studio.+ process = spawn_on_lifetime_thread(+ lambda: subprocess.Popen(+ [str(binary), "validate", "--json"],+ stdout = subprocess.PIPE,+ stderr = subprocess.PIPE,+ stdin = subprocess.DEVNULL,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ env = env,+ **windows_hidden_subprocess_kwargs(),+ **child_popen_kwargs(),+ )+ )+ except OSError as exc:+ return {"ready": False, "problems": [f"flm validate could not run: {exc}"]}+ adopt_pid(process.pid)+ self._validate_process = process+ # After adopting: a shutdown sweep that already ran would miss it.+ if self._closing.is_set() or is_process_shutting_down():+ _kill_tree(process)+ try:+ stdout, _stderr = process.communicate(timeout = 120)+ except subprocess.TimeoutExpired as exc:+ _kill_tree(process)+ process.communicate()+ return {"ready": False, "problems": [f"flm validate could not run: {exc}"]}+ finally:+ self._validate_process = None+ if process.poll() is not None:+ forget_pid(process.pid)+ try:+ report = json.loads(stdout)+ except ValueError:+ return {+ "ready": False,+ "problems": [f"flm validate returned no report: {stdout[-300:].strip()}"],+ }+ problems = [message for key, message in _VALIDATE_PROBLEMS if report.get(key) is False]+ ready = bool(report.get("ready"))+ if not ready and not problems:+ problems = ["NPU validation failed."]+ return {"ready": ready, "problems": problems, "report": report}++ def shutdown(self) -> None:+ self._closing.set()+ self.cancel_load()+ server = self._server+ if server is not None:+ server.stop()+ process = self._validate_process+ if process is not None:+ _kill_tree(process)+ with self._lock:+ self._loaded = None+ if self._server is not None:+ self._server.close()+ self._server = None+ if self._state not in ("failed",):+ self._state = "idle"+ self._closing.clear()++ def catalog(self) -> list[NpuModel]:+ server = self._ensure_running()+ response = server.request("GET", "/v1/models?show_all=true", timeout = 60.0)+ if _failed(response):+ raise NpuError(f"Listing NPU models failed: {_error_message(response)}")+ models: list[NpuModel] = []+ for row in response.json().get("data") or []:+ if not isinstance(row, dict) or row.get("recipe") != "flm":+ continue+ labels = tuple(str(label) for label in row.get("labels") or ())+ if "chat" not in labels or _EXCLUDED_LABELS.intersection(labels):+ continue+ size = row.get("size")+ models.append(+ NpuModel(+ id = str(row.get("id")),+ checkpoint = str(row.get("checkpoint") or ""),+ size_gb = float(size) if isinstance(size, (int, float)) else None,+ downloaded = bool(row.get("downloaded")),+ labels = labels,+ max_context_length = _positive_int(row.get("max_context_window")),+ )+ )+ return sorted(models, key = lambda model: (not model.downloaded, model.id))++ def _model(self, model_id: str) -> NpuModel:+ for model in self.catalog():+ if model.id == model_id:+ return model+ raise NpuError(f"{model_id} is not in the FastFlowLM catalog.")++ def loadable_model(self, model_id: str) -> NpuModel:+ """The catalog entry ``load`` would accept, checked before a caller unloads anything."""+ try:+ model = self._model(model_id)+ except LemonadeUnavailable as exc:+ raise NpuError(str(exc)) from exc+ if not model.downloaded:+ raise NpuError(f"{model.id} is not downloaded yet.")+ return model++ def download(self, model_id: str) -> Iterator[dict[str, Any]]:+ """Pull a model, yielding lemond's progress events, then a final ``complete`` one.++ Raises unless lemond sent its ``complete`` event: a stream cut short leaves a partial model.+ """+ model = self._model(model_id)+ server = self._ensure_running()+ event = "progress"+ completed = False+ with server.stream(+ "POST", "/v1/pull", json_body = {"model_name": model.id, "stream": True}+ ) as response:+ if response.status_code != 200:+ response.read()+ raise NpuError(f"Downloading {model.id} failed: {_error_message(response)}")+ for line in response.iter_lines():+ if line.startswith("event:"):+ event = line[len("event:") :].strip() or "progress"+ continue+ # A plain JSON body instead of a stream: lemond's HTTP 200 error answer.+ raw = line[len("data:") :] if line.startswith("data:") else line+ if not line.startswith("data:") and not line.startswith("{"):+ continue+ try:+ data = json.loads(raw.strip())+ except ValueError:+ continue+ if event == "error" or (isinstance(data, dict) and data.get("error")):+ message = data.get("error") if isinstance(data, dict) else data+ if isinstance(message, dict):+ message = message.get("message")+ raise NpuError(f"Downloading {model.id} failed: {message}")+ if isinstance(data, dict) and data.get("status") == "error":+ raise NpuError(f"Downloading {model.id} failed: {data.get('message') or data}")+ completed = completed or event == "complete"+ if isinstance(data, dict):+ yield {"event": event, **data}+ event = "progress"+ if not completed:+ raise NpuError(f"Downloading {model.id} ended before it completed.")+ yield {"event": "complete", "model": model.id, "percent": 100}++ def delete(self, model_id: str) -> None:+ with self._lock:+ resident = self.resident()+ if resident is not None and resident.model.id == model_id:+ raise NpuError("Unload the model before deleting it.")+ server = self._ensure_running()+ response = server.request("POST", "/v1/delete", json_body = {"model_name": model_id})+ if _failed(response):+ raise NpuError(f"Deleting {model_id} failed: {_error_message(response)}")++ def load(+ self,+ model_id: str,+ context_length: Optional[int] = None,+ ) -> NpuModel:+ """Load a downloaded model onto the NPU and return it once lemond reports it resident."""+ with self._lock:+ # Cleared before the load is published, so a cancel that sees it is never wiped.+ with self._commit_lock:+ self._load_cancelled.clear()+ self._loading = model_id+ replaced = False+ loaded = False+ try:+ model = self._model(model_id)+ if not model.downloaded:+ raise NpuError(f"{model.id} is not downloaded yet.")+ limit = model.max_context_length+ ctx = context_length if context_length and context_length > 0 else None+ ctx = ctx or min(DEFAULT_CONTEXT_LENGTH, limit or DEFAULT_CONTEXT_LENGTH)+ if limit:+ ctx = min(ctx, limit)+ server = self._ensure_running()+ replaced = True+ self._loaded = None+ self._raise_if_load_cancelled(model_id)+ response = server.request(+ "POST",+ "/v1/load",+ json_body = {"model_name": model.id, "ctx_size": ctx, "save_options": False},+ timeout = 900.0,+ )+ self._raise_if_load_cancelled(model_id)+ if _failed(response):+ raise NpuError(f"Loading {model.id} failed: {_error_message(response)}")+ resident_ctx = self._resident_context(server, model.id)+ if resident_ctx is None:+ raise NpuError(f"Lemonade did not report {model.id} as loaded on the NPU.")+ with self._commit_lock:+ self._raise_if_load_cancelled(model_id)+ self._loaded = _Loaded(+ model = model,+ context_length = resident_ctx,+ requested_context_length = (+ context_length if context_length and context_length > 0 else None+ ),+ )+ self._loading = None+ loaded = True+ self._state = "ready"+ self._error = None+ return model+ except LemonadeUnavailable as exc:+ self._raise_if_load_cancelled(model_id)+ raise NpuError(f"Loading {model_id} failed: {exc}") from exc+ finally:+ self._loading = None+ if replaced and not loaded and self._server is not None:+ # lemond may still hold the previous model, which Studio no longer records.+ self._server.stop()++ def _raise_if_load_cancelled(self, model_id: str) -> None:+ if self._load_cancelled.is_set():+ raise NpuLoadCancelled(f"Loading {model_id} was cancelled.")++ def cancel_load(self, model_id: Optional[str] = None) -> bool:+ """Stop an in-flight load by stopping lemond. Does not take the lock the load holds."""+ with self._commit_lock:+ loading = self._loading+ if loading is None or (model_id is not None and loading != model_id):+ return False+ self._load_cancelled.set()+ server = self._server+ if server is not None:+ server.stop()+ return True++ @staticmethod+ def _resident_context(server: LemonadeServer, model_id: str) -> Optional[int]:+ response = server.request("GET", "/v1/health", timeout = 30.0)+ if response.status_code != 200:+ return None+ for row in response.json().get("all_models_loaded") or []:+ if (+ isinstance(row, dict)+ and row.get("model_name") == model_id+ and row.get("device") == "npu"+ and row.get("loaded", True)+ ):+ options = row.get("recipe_options") or {}+ return _positive_int(options.get("ctx_size")) or DEFAULT_CONTEXT_LENGTH+ return None++ def unload(self) -> Optional[str]:+ """Unload the resident NPU model. Returns its model path, or None if nothing was loaded."""+ with self._lock:+ loaded = self._loaded+ self._loaded = None+ if loaded is None:+ return None+ server = self._server+ if server is not None and server.is_alive():+ try:+ response = server.request(+ "POST",+ "/v1/unload",+ json_body = {"model_name": loaded.model.id},+ timeout = 60.0,+ )+ failure = _error_message(response) if _failed(response) else None+ except LemonadeUnavailable as exc:+ failure = str(exc)+ if failure is not None:+ logger.warning(+ "Unloading %s from Lemonade failed: %s", loaded.model.id, failure+ )+ server.stop()+ return loaded.model.model_path++ def upstream(self) -> ManagedUpstream:+ # Lock-free: a chat must not wait behind an enable() or delete() holding the lock.+ resident = self.resident()+ if resident is None:+ raise NpuError("No NPU model is loaded.")+ model = resident.model+ return ManagedUpstream(+ provider_type = PROVIDER_TYPE,+ base_url = f"{resident.base_url}/v1",+ api_key = resident.api_key,+ model = model.id,+ public_model = model.model_path,+ supports_vision = model.vision,+ supports_tools = model.tools,+ supports_reasoning = model.reasoning,+ context_length = resident.context_length,+ )+++_backend: Optional[LemonadeNpuBackend] = None+_backend_lock = threading.Lock()+++def get_npu_backend() -> LemonadeNpuBackend:+ global _backend+ with _backend_lock:+ if _backend is None:+ _backend = LemonadeNpuBackend()+ return _backend+++def peek_npu_backend() -> Optional[LemonadeNpuBackend]:+ """The backend if anything has touched it, without creating one (for shutdown)."""+ return _backenddiff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.pyindex 161eb0fea91..8c415a179ea 100644--- a/studio/backend/core/inference/providers.py+++ b/studio/backend/core/inference/providers.py@@ -409,6 +409,22 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"supports_chat_template_kwargs": True,"hidden": True,},+ "lemonade": {+ "display_name": "AMD NPU (FastFlowLM)",+ "base_url": "",+ "default_models": [],+ "supports_streaming": True,+ "supports_vision": True,+ "supports_tool_calling": True,+ "studio_tools": True,+ "auth_header": "Authorization",+ "auth_prefix": "Bearer ",+ "notes": "Unsloth-managed Lemonade serving FastFlowLM on the AMD NPU.",+ # FastFlowLM 1.0.3 parses min_p into an integer, so 0.05 arrives as 0.+ "body_omit": ("min_p",),+ "hidden": True,+ "managed": True,+ },"openrouter": {"display_name": "OpenRouter","base_url": "https://openrouter.ai/api/v1",@@ -455,6 +471,12 @@ def get_provider_info(provider_type: str) -> dict[str, Any] | None:return PROVIDER_REGISTRY.get(provider_type)+def get_connectable_provider_info(provider_type: str) -> dict[str, Any] | None:+ """Return a user-configurable provider, excluding Studio-managed runtimes."""+ info = PROVIDER_REGISTRY.get(provider_type)+ return None if info is None or info.get("managed") else info++def get_base_url(provider_type: str) -> str | None:info = PROVIDER_REGISTRY.get(provider_type)return info["base_url"] if info else None@@ -1067,7 +1089,7 @@ def list_available_providers(include_hidden: bool = False) -> list[dict[str, Any"""result = []for provider_type, info in PROVIDER_REGISTRY.items():- if info.get("hidden") and not include_hidden:+ if (info.get("hidden") and not include_hidden) or info.get("managed"):continueresult.append({diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 997a7991583..36f1184ead8 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -351,6 +351,7 @@ from routes import (from routes.llama import router as llama_routerfrom routes.llama_compat import is_engine_probe_path, router as llama_compat_routerfrom routes.whisper import router as whisper_router+from routes.npu import router as npu_routerfrom routes.preview import router as preview_routerfrom hub.routes import (inventory_router as hub_inventory_router,@@ -1631,6 +1632,7 @@ app.include_router(datasets_router, prefix = "/api/datasets", tags = ["datasets"app.include_router(data_recipe_router, prefix = "/api/data-recipe", tags = ["data-recipe"])app.include_router(llama_router, prefix = "/api/llama", tags = ["llama"])app.include_router(whisper_router, prefix = "/api/whisper", tags = ["whisper"])+app.include_router(npu_router, prefix = "/api/npu", tags = ["npu"])app.include_router(export_router, prefix = "/api/export", tags = ["export"])app.include_router(rag_router, prefix = "/api/rag", tags = ["rag"])app.include_router(training_history_router, prefix = "/api/train", tags = ["training-history"])diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 47b988efa64..54342cf2867 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -1277,6 +1277,10 @@ class _InferenceRuntimeFields(BaseModel):),)is_mlx: bool = Field(False, description = "Whether the active model is served by the MLX backend")+ is_npu: bool = Field(+ False,+ description = "Whether the active model runs on the AMD Ryzen AI NPU (FastFlowLM through Lemonade)",+ )mlx_kv_bits: Optional[int] = Field(None, description = "MLX KV quantization bit width actually applied, if any")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8c9a00a377e..571b248b73a 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -7307,6 +7307,7 @@ def _llama_runtime_fields(llama_backend: LlamaCppBackend) -> dict:fields.update(# Not MLX, so the MLX runtime fields report as absent.is_mlx = False,+ is_npu = False,mlx_kv_bits = None,mlx_kv_bits_requested = None,mlx_kv_quant_eligibility = None,@@ -8920,7 +8921,15 @@ async def _no_model_loaded_error("""from utils.openai_auto_switch_settings import get_openai_auto_switch_enabledfrom core.inference.local_model_resolver import resolve_local_gguf+ from core.inference.npu_backend import peek_npu_backend+ _npu = peek_npu_backend()+ _npu_model = _npu.loaded_model if _npu is not None else None+ if _npu_model is not None:+ return 400, (+ f"The loaded NPU model ({_npu_model.model_path}) serves "+ "/v1/chat/completions only. Load a GGUF model to use this endpoint."+ )named = (requested_modelif isinstance(requested_model, str)@@ -9087,6 +9096,14 @@ def _resident_id_is_namespaced() -> bool:return any("/" in (public_model_id(c) or "") for c in candidates if c)+def _resident_npu_model():+ """The NPU model serving chat, or None. It answers to its own names only."""+ from core.inference.npu_backend import peek_npu_backend++ npu = peek_npu_backend()+ return npu.loaded_model if npu is not None else None++def _loaded_satisfies(requested: str) -> bool:"""Whether what is serving right now actually answers to *requested*.@@ -9095,6 +9112,9 @@ def _loaded_satisfies(requested: str) -> bool:"""from core.inference.openai_auto_download import looks_like_quant, split_model_ref+ npu_model = _resident_npu_model()+ if npu_model is not None:+ return requested in (npu_model.model_path, npu_model.id)base, variant = split_model_ref(requested)llama_backend = get_llama_cpp_backend()if getattr(llama_backend, "is_loaded", False):@@ -9147,6 +9167,9 @@ def _loaded_identity_satisfies(requested: str) -> bool:"""from core.inference.openai_auto_download import split_model_ref+ npu_model = _resident_npu_model()+ if npu_model is not None:+ return requested in (npu_model.model_path, npu_model.id)base, _ = split_model_ref(requested)llama_backend = get_llama_cpp_backend()if getattr(llama_backend, "is_loaded", False):@@ -9443,6 +9466,23 @@ async def _reject_unservable_model(warm_index_soon,)from utils.openai_auto_switch_settings import get_openai_auto_switch_enabled+ from core.inference.npu_backend import is_npu_model_path++ if is_npu_model_path(requested_model) and not await asyncio.to_thread(+ _loaded_satisfies, requested_model+ ):+ message = f"The NPU model '{requested_model}' is not loaded. Load it in Unsloth Studio."+ path = getattr(getattr(fastapi_request, "url", None), "path", None)+ raise HTTPException(+ status_code = 404,+ detail = (+ error_body_for_path(+ path, message, status = 404, code = "model_not_found", param = "model"+ )+ if isinstance(path, str)+ else message+ ),+ )still_indexing = Falsetry:@@ -9451,6 +9491,7 @@ async def _reject_unservable_model(if not (get_llama_cpp_backend().is_loadedor getattr(await asyncio.to_thread(get_inference_backend), "active_model_name", None)+ or _resident_npu_model() is not None):return# Refresh in the background and read the index as-is: scanning here would stall the@@ -10464,7 +10505,11 @@ def _loaded_slot_ident() -> Optional[str]:llama_backend = get_llama_cpp_backend()if llama_backend.is_loaded and llama_backend.model_identifier:return str(llama_backend.model_identifier)- return None+ from core.inference.npu_backend import peek_npu_backend++ npu = peek_npu_backend()+ npu_model = npu.loaded_model if npu is not None else None+ return npu_model.model_path if npu_model is not None else Nonedef release_chat_gpu_claim() -> bool:@@ -15807,6 +15852,118 @@ def _require_resolved_base_access(config) -> None:account_access.require_model_access(base.strip())+def _npu_load_response(resident, status: str) -> LoadResponse:+ model = resident.model+ return LoadResponse(+ status = status,+ model = model.model_path,+ display_name = model.id,+ is_npu = True,+ is_vision = model.vision,+ inference = load_inference_config(model.id),+ context_length = resident.context_length,+ max_context_length = model.max_context_length,+ native_context_length = model.max_context_length,+ context_length_enforced = True,+ supports_reasoning = model.reasoning,+ reasoning_style = "enable_thinking",+ supports_tools = model.tools,+ )+++async def _unload_npu_before_local_load() -> None:+ """Unload the NPU model before loading another local model."""+ from core.inference.npu_backend import peek_npu_backend++ npu = peek_npu_backend()+ if npu is not None and npu.is_loaded:+ logger.info("Unloading the NPU model before loading a local model")+ await asyncio.to_thread(npu.unload)+++async def _load_npu_model(+ request: LoadRequest,+ *,+ current_request_counted: bool,+ on_reload_confirmed,+ load_cancel_event: Optional[threading.Event],+) -> LoadResponse:+ """``/load`` for a ``lemonade:<id>`` model: the same swap rules as any local model."""+ from core.inference.npu_backend import (+ NpuError,+ NpuLoadCancelled,+ get_npu_backend,+ model_id_from_path,+ )+ from core.inference.llama_keepwarm import note_model_unloaded++ if account_access.managed_account():+ raise HTTPException(+ status_code = 403,+ detail = "The AMD NPU runtime is available to this installation's owner only.",+ )+ npu = get_npu_backend()+ try:+ model_id = model_id_from_path(request.model_path)+ except NpuError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+ requested_ctx = (+ request.max_seq_length if request.max_seq_length and request.max_seq_length > 0 else None+ )+ resident = npu.resident()+ if (+ resident is not None+ and resident.model.id == model_id+ and not request.force_reload+ # Exact: Auto after a pin, or a pin after Auto, is a different load.+ and requested_ctx == resident.requested_context_length+ ):+ account_access.join_resident("chat")+ return _npu_load_response(resident, "already_loaded")+ try:+ await asyncio.to_thread(npu.loadable_model, model_id)+ except NpuError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+ if load_cancel_event is not None and load_cancel_event.is_set():+ raise HTTPException(status_code = 409, detail = "Model load cancelled")+ if on_reload_confirmed is not None:+ on_reload_confirmed(cancel = True)+ if request.force_cancel_active:+ await _wait_for_model_switch_idle(+ current_request_counted = current_request_counted,+ timeout_s = _POST_CANCEL_DRAIN_TIMEOUT_S,+ )+ _set_preview_resident(None)+ await _unload_llama_before_standard_load(get_llama_cpp_backend())+ backend = _peek_inference_backend()+ if backend is not None and backend.active_model_name:+ logger.info(+ f"Unloading Unsloth model '{backend.active_model_name}' before loading on the NPU"+ )+ await asyncio.to_thread(backend.unload_model, backend.active_model_name)+ # Nothing to reload once idle: this model is not the one the idle stash names.+ note_model_unloaded()+ await asyncio.to_thread(release_chat_gpu_claim)+ if load_cancel_event is not None and load_cancel_event.is_set():+ raise HTTPException(status_code = 409, detail = "Model load cancelled")+ try:+ await asyncio.to_thread(npu.load, model_id, requested_ctx)+ except NpuLoadCancelled:+ raise HTTPException(status_code = 409, detail = "Model load cancelled") from None+ except NpuError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+ if load_cancel_event is not None and load_cancel_event.is_set():+ # Cancelled before npu.load marked itself in flight, so cancel_load found nothing to stop.+ await asyncio.to_thread(npu.unload)+ raise HTTPException(status_code = 409, detail = "Model load cancelled")+ resident = npu.resident()+ if resident is None:+ raise HTTPException(status_code = 409, detail = "Model load cancelled")+ account_access.publish_resident("chat", request.model_path)+ api_monitor.record_lifecycle(event = "load", model = request.model_path)+ return _npu_load_response(resident, "loaded")++async def _load_model_impl(request: LoadRequest,fastapi_request: Request,@@ -15820,6 +15977,15 @@ async def _load_model_impl(anonymous_hf_access: bool = False,speech_codec_path: Optional[str] = None,):+ from core.inference.npu_backend import is_npu_model_path++ if is_npu_model_path(request.model_path):+ return await _load_npu_model(+ request,+ current_request_counted = current_request_counted,+ on_reload_confirmed = on_reload_confirmed,+ load_cancel_event = load_cancel_event,+ )native_access_deferred = _defers_access_to_native_grant(request)if account_access.managed_account() and not native_access_deferred:await asyncio.to_thread(account_access.require_model_access, request.model_path)@@ -16596,6 +16762,7 @@ async def _load_model_impl(# ownership so a later preview for another checkpoint is not 503'd._restore_marker_if_prior_preview_still_resident()raise+ await _unload_npu_before_local_load()# Every rejection and source check has completed. The immutable# intent resolved before teardown is now the only launch input.@@ -16754,6 +16921,7 @@ async def _load_model_impl(# later preview for another checkpoint is not 503'd against it._restore_marker_if_prior_preview_still_resident()raise+ await _unload_npu_before_local_load()# Free the export's VRAM, but only when this load wants VRAM: a CPU load masks# the accelerators, so killing the user's export frees nothing it needs.@@ -18418,8 +18586,52 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):# next /v1 request can't resurrect this model. The idle loop unloads via the# backend directly (not this route), so clearing here never fights keep-warm.from core.inference.llama_keepwarm import inference_lifecycle_gate, note_model_unloaded+ from core.inference.npu_backend import MODEL_PREFIX, is_npu_model_path, peek_npu_backendtry:+ if is_npu_model_path(request.model_path):+ if account_access.managed_account():+ # Only the owner loads NPU models, so no managed account shares or stops one.+ raise HTTPException(status_code = 404, detail = "Model not found")+ npu = peek_npu_backend()+ requested_id = request.model_path[len(MODEL_PREFIX) :].strip()+ if request.cancel_load_request_id is not None:+ # Bound to that attempt: an early cancel leaves a tombstone, a stale one stops nothing newer.+ attempt, is_running = _cancel_scoped_load_attempt(request, current_subject)+ if attempt is not None and is_running:+ try:+ if npu is not None and await asyncio.to_thread(+ npu.cancel_load, requested_id+ ):+ logger.info(+ f"Cancelled scoped in-flight NPU load: {request.model_path}"+ )+ finally:+ attempt.cancel_complete.set()+ return UnloadResponse(status = "unloaded", model = request.model_path)+ # "Stop loading": /load holds the lifecycle gate until /v1/load returns.+ if npu is not None and await asyncio.to_thread(npu.cancel_load, requested_id):+ logger.info(f"Cancelled in-flight NPU load: {request.model_path}")+ return UnloadResponse(status = "unloaded", model = request.model_path)+ async with inference_lifecycle_gate():+ # Only the named model: another tab may have replaced it since.+ npu_model = npu.loaded_model if npu is not None else None+ if npu_model is not None and npu_model.id == requested_id:+ _raise_or_cancel_active_generations(+ force = request.force_cancel_active, action = "Unloading the model"+ )+ await _drain_and_recancel_before_teardown(+ force = request.force_cancel_active, action = "Unloading the model"+ )+ await asyncio.to_thread(npu.unload)+ note_model_unloaded()+ account_access.clear_resident("chat")+ api_monitor.record_lifecycle(+ event = "unload", model = request.model_path, reason = "manual"+ )+ logger.info(f"Unloaded NPU model: {request.model_path}")+ return UnloadResponse(status = "unloaded", model = request.model_path)+# Hidden Audio cleanup is cancellation, not a manual eject. Bind it to the# exact client load attempt so a delayed request can never stop a newer# same-model load or unload a model that has already become resident.@@ -19189,6 +19401,31 @@ async def get_status(current_subject: str):_loading = [_tracked_loading_id] if _tracked_loading_id else []backend = _peek_inference_backend()+ from core.inference.npu_backend import peek_npu_backend++ _npu = peek_npu_backend()+ _npu_resident = _npu.resident() if _npu is not None else None+ if _npu_resident is not None:+ _npu_model = _npu_resident.model+ return InferenceStatusResponse(+ active_model = _npu_model.id,+ model_identifier = _npu_model.model_path,+ is_npu = True,+ is_vision = _npu_model.vision,+ loading = _loading,+ loaded = [_npu_model.model_path],+ inference = load_inference_config(_npu_model.id),+ context_length = _npu_resident.context_length,+ requested_context_length = _npu_resident.requested_context_length,+ max_context_length = _npu_model.max_context_length,+ native_context_length = _npu_model.max_context_length,+ context_length_enforced = True,+ supports_reasoning = _npu_model.reasoning,+ reasoning_style = "enable_thinking",+ supports_tools = _npu_model.tools,+ llama_cpp_supports_mtp = _supports_mtp,+ )+# If a GGUF model is loaded via llama-server, report thatif llama_backend.is_loaded:_model_id = llama_backend.model_identifier@@ -23059,16 +23296,91 @@ def _safe_retry_after_header(value: Any) -> Optional[str]:return candidate+def _sse_line_finishes(line: str) -> bool:+ """Whether an OpenAI stream line carries a choice's finish_reason."""+ raw = line[len("data:") :].strip() if line.startswith("data:") else line+ try:+ chunk = json.loads(raw)+ except ValueError:+ return False+ return isinstance(chunk, dict) and any(+ isinstance(choice, dict) and choice.get("finish_reason")+ for choice in chunk.get("choices") or ()+ )+++class _TurnFinish:+ """Whether a stream's last provider turn carried a finish_reason (the tool loop relays intermediate ones)."""++ def __init__(self) -> None:+ self.turn = False+ self.last: bool | None = None++ def see(self, line: str) -> None:+ if not self.turn:+ self.turn = _sse_line_finishes(line)++ def end_turn(self) -> None:+ self.last, self.turn = self.turn, False++ @property+ def finished(self) -> bool:+ return self.turn or bool(self.last)+++async def _stop_on_cancel(agen, cancel_event: threading.Event):+ """Yield from ``agen`` until ``cancel_event`` is set, even while it waits for a frame.++ A managed runtime can prefill for seconds before its first frame, and a check between frames+ leaves a cancelled generation holding the model through a swap's teardown.+ """++ async def _cancelled() -> None:+ while not cancel_event.is_set():+ await asyncio.sleep(0.1)++ waiter = asyncio.ensure_future(_cancelled())+ step = None+ try:+ while True:+ step = asyncio.ensure_future(agen.__anext__())+ done, _ = await asyncio.wait({step, waiter}, return_when = asyncio.FIRST_COMPLETED)+ if step not in done:+ return+ try:+ line = step.result()+ except StopAsyncIteration:+ return+ yield line+ finally:+ for task in (step, waiter):+ if task is not None and not task.done():+ # Cancelling the pending read closes the upstream response inside ``agen``.+ task.cancel()+ await asyncio.gather(task, return_exceptions = True)+ try:+ await agen.aclose()+ except RuntimeError:+ pass++async def _proxy_to_external_provider(payload: ChatCompletionRequest,request: Request,current_subject: Optional[str] = None,+ *,+ managed = None,+ early_close_status = None,) -> Response:"""Proxy a chat completion request to an external LLM provider.Resolves provider config (DB or registry), decrypts the API key, and returnseither one Chat Completion JSON object or an OpenAI-compatible SSE stream.++ Managed upstreams supply server-owned routing and credentials. Their streams are+ tracked for cancellation during model swaps. ``early_close_status`` names the monitor+ status for a consumer closing the stream before it ends ("cancelled" when omitted)."""# Resolve provider type and base URLprovider_type = payload.provider_type@@ -23076,7 +23388,11 @@ async def _proxy_to_external_provider(api_type = payload.provider_api_typesaved_provider_snapshot: Optional[dict] = None- if payload.provider_id and not payload.encrypted_api_key:+ if managed is not None:+ provider_type = managed.provider_type+ base_url = managed.base_url+ api_type = "chat_completions"+ elif payload.provider_id and not payload.encrypted_api_key:# Saved-provider SQLite reads must not block the event loop.config = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)if config is None:@@ -23115,6 +23431,7 @@ async def _proxy_to_external_provider(# native translator, so entering the loop for them would advertise tools# the model is never shown and finish as if none were selected.provider_model_runs_local_tools(provider_type, payload.external_model or payload.model)+ and (managed is None or managed.supports_tools)and payload.stream is Trueand _explicit_studio_tool_loop_requested(payload)# A selection of purely hosted names is the provider's tool envelope, not@@ -23163,10 +23480,8 @@ async def _proxy_to_external_provider(param = "confirm_tool_calls",),)- # Fall back to registry default base URL. The registry lookup is checked on- # its own: a caller-supplied base_url used to make an unknown provider_type- # pass straight through to the proxy.- if get_provider_info(provider_type) is None:+ _provider_info_entry = get_provider_info(provider_type)+ if _provider_info_entry is None or (managed is None and _provider_info_entry.get("managed")):raise HTTPException(status_code = 400,detail = f"Unknown provider type: {provider_type}",@@ -23179,11 +23494,12 @@ async def _proxy_to_external_provider(detail = f"Base URL is required for provider type: {provider_type}",)# Validate the proxy destination before the API key is decrypted, so a- # refused target never sees a credential.- try:- base_url = validate_provider_base_url(base_url)- except ValueError as exc:- raise HTTPException(status_code = 400, detail = str(exc)) from None+ # refused target never sees a credential. A managed upstream is Unsloth's own loopback.+ if managed is None:+ try:+ base_url = validate_provider_base_url(base_url)+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from Noneif provider_type == "openai_codex":from core.inference.openai_codex_auth import (@@ -23632,7 +23948,9 @@ async def _proxy_to_external_provider()api_key: Optional[str] = None- if saved_provider_snapshot is not None:+ if managed is not None:+ api_key = managed.api_key+ elif saved_provider_snapshot is not None:async with provider_config_guard(payload.provider_id):current = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)routing_fields = ("provider_type", "base_url", "api_type", "is_enabled")@@ -23668,7 +23986,7 @@ async def _proxy_to_external_provider(),)- model = payload.external_model or payload.model+ model = managed.model if managed is not None else (payload.external_model or payload.model)if model == "default":raise HTTPException(status_code = 400,@@ -23679,7 +23997,9 @@ async def _proxy_to_external_provider(from core.inference.providers import get_provider_info as _get_provider_info_pinfo = _get_provider_info(provider_type) or {}- _supports_vision = _pinfo.get("supports_vision", False)+ _supports_vision = (+ managed.supports_vision if managed is not None else _pinfo.get("supports_vision", False)+ )_external_promoted_parts: list = []chat_messages = await _build_external_messages_async(payload.messages,@@ -23703,9 +24023,9 @@ async def _proxy_to_external_provider(endpoint = request.url.path,via_api_key = _request_used_api_key(request),method = request.method,- model = model,+ model = managed.public_model if managed is not None else model,prompt = _monitor_prompt_from_messages(payload.messages),- context_length = None,+ context_length = managed.context_length if managed is not None else None,subject = current_subject,)@@ -23714,19 +24034,21 @@ async def _proxy_to_external_provider(base_url = base_url,api_key = api_key,api_type = api_type,+ **({"managed_loopback": True} if managed is not None else {}),)_non_stream_custom_responses = (provider_type == "custom" and api_type == "responses" and payload.stream is False)- # Schema defaults are non-None (20, 0.01, 1.0) for the local path, so only- # `model_fields_set` separates "asked for 20" from "said nothing", and the provider keeps- # its own default for the latter. Read before ANY write: a setattr marks a field explicit.- _top_p_explicit = payload.top_p if "top_p" in payload.model_fields_set else None- _top_k_explicit = payload.top_k if "top_k" in payload.model_fields_set else None+ # Always send defaults to FastFlowLM, which otherwise reuses the previous request's values.+ _always_send = managed is not None+ _top_p_explicit = payload.top_p if _always_send or "top_p" in payload.model_fields_set else None+ _top_k_explicit = payload.top_k if _always_send or "top_k" in payload.model_fields_set else None_min_p_explicit = payload.min_p if "min_p" in payload.model_fields_set else None_repetition_penalty_explicit = (- payload.repetition_penalty if "repetition_penalty" in payload.model_fields_set else None+ payload.repetition_penalty+ if _always_send or "repetition_penalty" in payload.model_fields_set+ else None)# Unsloth-owned tool loop for every non-Codex provider that declares the@@ -23808,6 +24130,8 @@ async def _proxy_to_external_provider(fast_mode = payload.fast_mode,response_format = _extract_response_format(payload),)+ # A managed runtime that drops a reply still closes with [DONE]; it is cut short, not done.+ managed_finish = _TurnFinish()if run_studio_tool_loop:# The Unsloth loop owns the tool surface for this turn. The caller's# own catalog is dropped for the same reason the Codex path drops it@@ -23829,6 +24153,12 @@ async def _proxy_to_external_provider(else provider_type)loop_hosted_tools = hosted_only_tools(hosted_provider_type, payload.enabled_tools)++ def _end_provider_turn() -> None:+ managed_finish.end_turn()+ if not _ui_events:+ _tool_call_stripper.end_turn()+gen = stream_with_studio_tools(OAICompatTransport(client,@@ -23872,7 +24202,7 @@ async def _proxy_to_external_provider(# Matches the strip below: only a headerless caller has its calls# withheld, so only it needs a healed one the wire never carried flagged.on_withheld_tool_call = (None if _ui_events else _tool_call_stripper.arm),- on_provider_turn_end = (None if _ui_events else _tool_call_stripper.end_turn),+ on_provider_turn_end = _end_provider_turn,),cancel_event = cancel_event,)@@ -23887,11 +24217,33 @@ async def _proxy_to_external_provider(stream = payload.stream,**_provider_kwargs,)+ if managed is not None:+ # Stopping the read stops FastFlowLM, which a model swap is waiting on.+ gen = _stop_on_cancel(gen, cancel_event)disconnect_task = asyncio.create_task(_watch_disconnect()) if run_studio_tool_loop else None++ def _managed_cut_short() -> bool:+ return (+ managed is not None+ and not stream_failed+ and not managed_finish.finished+ and not cancel_event.is_set()+ )++ def _fail_cut_short() -> str:+ api_monitor.fail(monitor_id, _NPU_CUT_SHORT_ERROR["message"])+ return "data: " + json.dumps({"error": dict(_NPU_CUT_SHORT_ERROR)}) + "\n\n"+try:sent_done = Falsestream_failed = Falseasync for line in gen:+ if _is_openai_sse_done(line) and _managed_cut_short():+ # Before [DONE] reaches the monitor, which would record the reply completed.+ yield _fail_cut_short()+ stream_failed = True+ if managed is not None:+ managed_finish.see(line)monitor_event = _monitor_openai_sse_line(monitor_id, line)if monitor_event is None:try:@@ -23937,8 +24289,26 @@ async def _proxy_to_external_provider(# the GGUF passthrough places its own synthetic finish._owed = _tool_call_stripper.owed_terminal_chunk()if _owed is not None and not stream_failed:+ managed_finish.see(_owed)_monitor_openai_sse_line(monitor_id, _owed)yield f"{_owed}\n\n"+ if not sent_done and _managed_cut_short():+ yield _fail_cut_short()+ stream_failed = True+ if managed is not None and cancel_event.is_set() and not sent_done:+ yield (+ "data: "+ + json.dumps(+ {+ "id": f"chatcmpl-{uuid.uuid4().hex}",+ "object": "chat.completion.chunk",+ "created": int(time.time()),+ "model": model,+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ }+ )+ + "\n\n"+ )if not sent_done:if not stream_failed:_monitor_openai_sse_line(monitor_id, "data: [DONE]")@@ -23946,6 +24316,11 @@ async def _proxy_to_external_provider(except asyncio.CancelledError:api_monitor.finish(monitor_id, "cancelled")raise+ except GeneratorExit:+ api_monitor.finish(+ monitor_id, early_close_status() if early_close_status else "cancelled"+ )+ raiseexcept Exception as exc:logger.error("external_provider.stream_error", error = str(exc))api_monitor.fail(monitor_id, _friendly_error(exc))@@ -23980,16 +24355,18 @@ async def _proxy_to_external_provider(await client.close()def _tracked_stream():- # Only the tool loop is registered: it can run for minutes and a /load- # needs to know it would interrupt a chat. The plain proxy stays- # untracked, as it was before.- if not run_studio_tool_loop:+ if not run_studio_tool_loop and managed is None:return _stream()async def _wrapped():+ inner = _stream()with _TrackedCancel.for_payload(cancel_event, payload, *cancel_keys):- async for chunk in _stream():- yield chunk+ try:+ async for chunk in inner:+ yield chunk+ finally:+ # Close it now, not at garbage collection: that releases the upstream request.+ await inner.aclose()return _wrapped()@@ -24047,6 +24424,324 @@ async def _proxy_to_external_provider()+_NPU_CUT_SHORT_ERROR = {+ "message": "The NPU model stopped before finishing its reply.",+ "type": "upstream_error",+}+++class _NpuStreamRelay:+ """Normalize model IDs, enforce stop sequences, and collect non-streaming replies.++ FastFlowLM ignores stop sequences, so buffer partial matches until resolved.+ """++ def __init__(self, public_model: str, stop: Optional[list[str]]) -> None:+ self.public_model = public_model+ self.stop = stop or []+ self._pending = ""+ self.stopped = False+ self.content = ""+ self.reasoning = ""+ self.tool_calls: dict[int, dict] = {}+ self.finish_reason: Optional[str] = None+ self.usage: Optional[dict] = None+ self.error: Optional[dict] = None+ self.completion_id: Optional[str] = None+ self.created: Optional[int] = None++ def _held_back(self, text: str) -> int:+ """Length of the longest tail of ``text`` that begins some stop sequence."""+ longest = 0+ for stop in self.stop:+ for size in range(min(len(stop) - 1, len(text)), 0, -1):+ if stop.startswith(text[-size:]):+ longest = max(longest, size)+ break+ return longest++ def _take_content(self, text: str) -> str:+ buffer = self._pending + text+ hits = [index for index in (buffer.find(stop) for stop in self.stop) if index >= 0]+ if hits:+ self._pending = ""+ self.stopped = True+ return buffer[: min(hits)]+ keep = self._held_back(buffer)+ self._pending = buffer[len(buffer) - keep :] if keep else ""+ return buffer[: len(buffer) - keep] if keep else buffer++ def _chunk(self, delta: dict, finish_reason: Optional[str]) -> str:+ return "data: " + json.dumps(+ {+ "id": self.completion_id or "chatcmpl-npu",+ "object": "chat.completion.chunk",+ "created": self.created or int(time.time()),+ "model": self.public_model,+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],+ }+ )++ def feed(self, line: str) -> list[str]:+ """The lines to send on for one line of the upstream stream."""+ if not line.startswith("data:"):+ return [line]+ raw = line[len("data:") :].strip()+ if raw == "[DONE]":+ out = []+ if self._pending:+ self.content += self._pending+ out.append(self._chunk({"content": self._pending}, None))+ self._pending = ""+ out.append(line)+ return out+ try:+ chunk = json.loads(raw)+ except ValueError:+ return [line]+ if not isinstance(chunk, dict):+ return [line]+ if "error" in chunk:+ self.error = (+ chunk["error"]+ if isinstance(chunk["error"], dict)+ else {"message": str(chunk["error"])}+ )+ return [line]+ self.completion_id = self.completion_id or chunk.get("id")+ self.created = self.created or chunk.get("created")+ if "model" in chunk:+ chunk["model"] = self.public_model+ if isinstance(chunk.get("usage"), dict):+ self.usage = chunk["usage"]+ out: list[str] = []+ for choice in chunk.get("choices") or []:+ if not isinstance(choice, dict):+ continue+ delta = choice.get("delta") if isinstance(choice.get("delta"), dict) else {}+ reasoning = delta.get("reasoning_content")+ if isinstance(reasoning, str):+ self.reasoning += reasoning+ for call in delta.get("tool_calls") or []:+ if not isinstance(call, dict):+ continue+ slot = self.tool_calls.setdefault(+ int(call.get("index", len(self.tool_calls))),+ {"id": None, "type": "function", "function": {"name": "", "arguments": ""}},+ )+ slot["id"] = call.get("id") or slot["id"]+ function = call.get("function") or {}+ slot["function"]["name"] += function.get("name") or ""+ slot["function"]["arguments"] += function.get("arguments") or ""+ content = delta.get("content")+ if isinstance(content, str) and self.stop:+ visible = self._take_content(content)+ self.content += visible+ delta["content"] = visible+ if self.stopped:+ self.finish_reason = "stop"+ choice["finish_reason"] = None+ out.append("data: " + json.dumps(chunk))+ out.append(self._chunk({}, "stop"))+ out.append("data: [DONE]")+ return out+ elif isinstance(content, str):+ self.content += content+ if choice.get("finish_reason") is not None:+ self.finish_reason = choice["finish_reason"]+ if self._pending:+ # The reply ended partway into a stop sequence, so what was held back is text.+ delta["content"] = (delta.get("content") or "") + self._pending+ self.content += self._pending+ self._pending = ""+ choice["delta"] = delta+ out.append("data: " + json.dumps(chunk))+ return out++ def completion(self) -> dict:+ message: dict[str, Any] = {"role": "assistant", "content": self.content or None}+ if self.reasoning:+ message["reasoning_content"] = self.reasoning+ if self.tool_calls:+ message["tool_calls"] = [self.tool_calls[index] for index in sorted(self.tool_calls)]+ body = {+ "id": self.completion_id or f"chatcmpl-{uuid.uuid4().hex}",+ "object": "chat.completion",+ "created": self.created or int(time.time()),+ "model": self.public_model,+ "choices": [+ {+ "index": 0,+ "message": message,+ "finish_reason": self.finish_reason or "stop",+ "logprobs": None,+ }+ ],+ }+ if self.usage is not None:+ body["usage"] = self.usage+ return body+++async def _npu_chat_completions(payload, request: Request, current_subject: str):+ """Proxy NPU chat, rejecting unsupported parameters.++ Always stream upstream: FastFlowLM's non-streaming replies mishandle reasoning+ and finish reasons on length cutoffs. Collect the stream for JSON callers.+ """+ from core.inference.npu_backend import NpuError, get_npu_backend++ try:+ upstream = await asyncio.to_thread(get_npu_backend().upstream)+ except NpuError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+ if _wants_multiple_choices(payload):+ _raise_unsupported_n("NPU chat completions")+ if _response_format_constrains_decoding(payload):+ _raise_unsupported_openai_parameter(+ "response_format", "FastFlowLM on the NPU has no guided decoding for response_format."+ )+ if getattr(payload, "seed", None) is not None:+ _raise_unsupported_openai_parameter(+ "seed", "FastFlowLM on the NPU does not take a sampling seed."+ )+ if getattr(payload, "frequency_penalty", 0.0):+ _raise_unsupported_openai_parameter(+ "frequency_penalty", "FastFlowLM on the NPU does not take a frequency penalty."+ )+ if getattr(payload, "logit_bias", None):+ _raise_unsupported_openai_parameter(+ "logit_bias", "FastFlowLM on the NPU does not take a logit bias."+ )+ if payload.logprobs or payload.top_logprobs is not None:+ _raise_unsupported_openai_parameter(+ "logprobs", "FastFlowLM on the NPU does not report log probabilities."+ )+ if (+ _request_has_video(payload)+ or payload.audio_base64+ or _messages_have_input_audio(payload.messages)+ ):+ raise HTTPException(+ status_code = 400, detail = "Audio and video input are not supported on the NPU."+ )+ if not upstream.supports_vision and _request_has_attached_image(payload):+ raise HTTPException(+ status_code = 400,+ detail = "This NPU model does not read images. Load a vision model to send one.",+ )+ if payload.tool_choice == "none":+ # FastFlowLM 1.0.3 ignores tool_choice and calls a tool anyway.+ payload.tools = None+ elif payload.tools and payload.parallel_tool_calls is False:+ _raise_unsupported_openai_parameter(+ "parallel_tool_calls", "FastFlowLM on the NPU cannot limit a reply to one tool call."+ )+ elif payload.tools and payload.tool_choice not in (None, "auto"):+ _raise_unsupported_openai_parameter(+ "tool_choice", "FastFlowLM on the NPU chooses its own tool; use auto or none."+ )+ elif payload.tools and not upstream.supports_tools:+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(+ "This NPU model does not support tool calling.",+ status = 400,+ code = "unsupported_parameter",+ param = "tools",+ ),+ )++ _fill_recommended_sampling_openai(payload, upstream.model)+ _normalize_chat_reasoning_controls(payload)+ if not upstream.supports_reasoning:+ payload.enable_thinking = False+ elif payload.enable_thinking is None:+ payload.enable_thinking = payload.reasoning_effort != "none"++ wants_stream = bool(payload.stream)+ relay = _NpuStreamRelay(upstream.public_model, _normalize_stop_sequences(payload.stop))+ update: dict = {"stream": True}+ if _legacy_image_is_distinct(payload):+ # The proxy reads messages only, so splice a top-level image in as GGUF chat does.+ update["messages"] = [+ ChatMessage.model_validate(message)+ for message in _openai_messages_for_passthrough(payload, vision = True)+ ]+ upstream_payload = payload.model_copy(update = update)+ response = await _proxy_to_external_provider(+ upstream_payload,+ request,+ current_subject,+ managed = upstream,+ early_close_status = lambda: "completed" if relay.stopped else "cancelled",+ )++ async def _lines():+ body = response.body_iterator+ try:+ async for piece in body:+ text = piece.decode("utf-8") if isinstance(piece, bytes) else piece+ for line in text.split("\n"):+ if line.strip():+ yield line+ finally:+ await body.aclose()++ if wants_stream:++ async def _stream():+ lines = _lines()+ try:+ async for line in lines:+ for out in relay.feed(line):+ yield f"{out}\n\n"+ if relay.stopped:+ return+ finally:+ await lines.aclose()++ return StreamingResponse(+ _stream(),+ media_type = "text/event-stream",+ headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )++ # Nothing cancels a handler whose caller left, so watch for it: FastFlowLM is the one runtime.+ disconnected = threading.Event()++ async def _watch_disconnect() -> None:+ while not disconnected.is_set():+ if await request.is_disconnected():+ disconnected.set()+ return+ await asyncio.sleep(0.25)++ watcher = asyncio.create_task(_watch_disconnect())+ lines = _stop_on_cancel(_lines(), disconnected)+ try:+ async for line in lines:+ relay.feed(line)+ if relay.stopped or relay.error is not None:+ break+ finally:+ watcher.cancel()+ await asyncio.gather(watcher, return_exceptions = True)+ await lines.aclose()+ if disconnected.is_set():+ return Response(status_code = 499)+ if relay.error is not None:+ try:+ status = int(relay.error.get("code") or 502)+ except (TypeError, ValueError):+ status = 502+ status = status if 400 <= status < 600 else 502+ return JSONResponse(status_code = status, content = {"error": relay.error})+ if relay.finish_reason is None:+ return JSONResponse(status_code = 502, content = {"error": dict(_NPU_CUT_SHORT_ERROR)})+ return JSONResponse(content = relay.completion())++# ── OpenAI shell-tool container management ───────────────────────@@ -24840,6 +25535,12 @@ async def produce_openai_chat_completions(_predecoded_audio = _audio_preflight.get("decoded")_preprepared_audio = _audio_preflight.get("prepared")+ from core.inference.npu_backend import peek_npu_backend++ _npu = peek_npu_backend()+ if _npu is not None and _npu.is_loaded:+ return await _npu_chat_completions(payload, request, current_subject)+llama_backend = get_llama_cpp_backend()using_gguf = llama_backend.is_loaded@@ -29246,6 +29947,25 @@ def _openai_model_objects() -> list[dict]:models: list[dict] = []_created = int(time.time())+ from core.inference.npu_backend import peek_npu_backend++ _npu = peek_npu_backend()+ _npu_resident = _npu.resident() if _npu is not None else None+ if _npu_resident is not None:+ _npu_model = _npu_resident.model+ _npu_entry = {+ "id": _npu_model.model_path,+ "object": "model",+ "created": _created,+ "owned_by": _OWNED_BY,+ "device": "npu",+ }+ if _npu_resident.context_length:+ _npu_entry["context_length"] = _npu_resident.context_length+ if _npu_model.max_context_length:+ _npu_entry["max_context_length"] = _npu_model.max_context_length+ models.append(_npu_entry)+# Check GGUF backendllama_backend = get_llama_cpp_backend()# Claiming a re-pulled tag would displace the scanned row holding its weights, and the id@@ -34154,6 +34874,16 @@ async def chat_count_tokens(detail = "Cannot count tokens for messages containing images.",)+ from core.inference.npu_backend import peek_npu_backend++ _npu = peek_npu_backend()+ if _npu is not None and _npu.is_loaded:+ # FastFlowLM has no tokenizer endpoint; each reply's usage still reports the prompt size.+ raise HTTPException(+ status_code = 503,+ detail = "Token counting is not available for NPU models.",+ )+llama_backend = get_llama_cpp_backend()if not llama_backend.is_loaded:# The refusals above are about the request and so are shared; the ones below arediff --git a/studio/backend/routes/npu.py b/studio/backend/routes/npu.pynew file mode 100644index 00000000000..26cdfddc1cb--- /dev/null+++ b/studio/backend/routes/npu.py@@ -0,0 +1,154 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""NPU detection, setup and model management.++Loading and chat use the inference routes. All routes here except status are owner-only.+"""++from __future__ import annotations++import asyncio+import json+import threading++from fastapi import APIRouter, Depends, HTTPException+from fastapi.responses import StreamingResponse+from starlette.concurrency import iterate_in_threadpool++from auth import policy+from auth.authentication import get_current_subject+from core.inference.npu_backend import NpuError, get_npu_backend+from hub.services.models import account_access++router = APIRouter()++_MANAGED_ACCOUNT_STATUS = {+ "supported": False,+ "hardware": {"present": False, "supported": False},+ "runtime_installed": False,+ "runtime_running": False,+ "state": "idle",+ "ready": False,+ "error": None,+ "validation": None,+ "help_url": None,+ "loaded_model": None,+ "context_length": None,+ "loading_model": None,+}+++async def _require_installation_owner(current_subject: str = Depends(get_current_subject)) -> None:+ await policy.require_owner()+++class _Download:+ """One pull, run off the request so a dropped progress stream does not stop it."""++ def __init__(self) -> None:+ self.events: list[dict] = []+ self.finished = False+ self.changed = threading.Condition()++ def publish(self, event: dict) -> None:+ with self.changed:+ self.events.append(event)+ self.changed.notify_all()++ def follow(self):+ """Every event so far, then each new one, until the pull ends."""+ seen = 0+ while True:+ with self.changed:+ while seen >= len(self.events) and not self.finished:+ self.changed.wait()+ batch, seen = self.events[seen:], len(self.events)+ finished = self.finished+ yield from batch+ if finished:+ return+++_downloads: dict[str, _Download] = {}+_downloads_lock = threading.Lock()+++def _start_download(npu, model_id: str) -> _Download:+ """The model's running pull, or a new one; a second request follows the first."""+ with _downloads_lock:+ job = _downloads.get(model_id)+ if job is not None and not job.finished:+ return job+ job = _Download()+ _downloads[model_id] = job++ def _run() -> None:+ try:+ for event in npu.download(model_id):+ job.publish(event)+ except NpuError as exc:+ job.publish({"event": "error", "error": str(exc)})+ except Exception as exc: # noqa: BLE001 -- reported on the stream, not lost in a thread+ job.publish({"event": "error", "error": f"Downloading {model_id} failed: {exc}"})+ finally:+ with job.changed:+ job.finished = True+ job.changed.notify_all()++ threading.Thread(target = _run, daemon = True, name = "npu-pull").start()+ return job++[email protected]("/status")+async def npu_status(current_subject: str = Depends(get_current_subject)):+ """Whether this machine has a supported NPU, and the runtime's state. Never starts anything."""+ if account_access.managed_account():+ return dict(_MANAGED_ACCOUNT_STATUS)+ return await asyncio.to_thread(get_npu_backend().status)++[email protected]("/enable", dependencies = [Depends(_require_installation_owner)])+async def enable_npu():+ """Install and start Lemonade, install FastFlowLM and validate the NPU. Idempotent."""+ try:+ return await asyncio.to_thread(get_npu_backend().enable)+ except NpuError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None++[email protected]("/models", dependencies = [Depends(_require_installation_owner)])+async def list_npu_models():+ try:+ models = await asyncio.to_thread(get_npu_backend().catalog)+ except NpuError as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from None+ return {"models": [model.to_json() for model in models]}++[email protected]("/models/{model_id}/download", dependencies = [Depends(_require_installation_owner)])+async def download_npu_model(model_id: str):+ """Stream download progress through a final complete or error event.++ Disconnecting stops progress updates, not the download.+ """+ job = _start_download(get_npu_backend(), model_id)++ def _events():+ for event in job.follow():+ yield f"data: {json.dumps(event)}\n\n"++ return StreamingResponse(+ iterate_in_threadpool(_events()),+ media_type = "text/event-stream",+ headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )++[email protected]("/models/{model_id}", dependencies = [Depends(_require_installation_owner)])+async def delete_npu_model(model_id: str):+ try:+ await asyncio.to_thread(get_npu_backend().delete, model_id)+ except NpuError as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from None+ return {"status": "deleted", "model": model_id}diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex 4f949bfb25b..5f5a50b9533 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -33,6 +33,7 @@ from core.inference.key_exchange import ()from core.inference.providers import (get_base_url,+ get_connectable_provider_info,get_provider_info,list_available_providers,validate_provider_base_url,@@ -221,7 +222,7 @@ async def create_provider_config("""Create a saved provider configuration and optional encrypted API key."""require_ui_session(via_api_key)- info = get_provider_info(payload.provider_type)+ info = get_connectable_provider_info(payload.provider_type)if info is None:raise HTTPException(status_code = 400,@@ -765,7 +766,7 @@ async def test_provider("""payload = _bind_saved_provider_target(payload)- info = get_provider_info(payload.provider_type)+ info = get_connectable_provider_info(payload.provider_type)if info is None:raise HTTPException(status_code = 400,@@ -912,7 +913,7 @@ async def list_provider_model_capabilities(via_api_key: bool = Depends(authenticated_via_api_key),):payload = _bind_saved_provider_target(payload)- info = get_provider_info(payload.provider_type)+ info = get_connectable_provider_info(payload.provider_type)if info is None:raise HTTPException(status_code = 400,@@ -975,7 +976,7 @@ async def list_provider_models("""payload = _bind_saved_provider_target(payload)- info = get_provider_info(payload.provider_type)+ info = get_connectable_provider_info(payload.provider_type)if info is None:raise HTTPException(status_code = 400,diff --git a/studio/backend/run.py b/studio/backend/run.pyindex c9d9590697e..c422cc07a13 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -1509,6 +1509,15 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error shutting down llama-server: %s", e)+ try:+ from core.inference.npu_backend import peek_npu_backend+ _npu = peek_npu_backend()+ if _npu is not None:+ # Unload first: lemond then stops FastFlowLM itself, before the tree kill.+ _npu.shutdown()+ except Exception as e:+ logger.warning("Error shutting down the NPU runtime: %s", e)+try:from cloudflare_tunnel import close_studio_tunnel_lifecycleclose_studio_tunnel_lifecycle()diff --git a/studio/backend/tests/fixtures/fake_lemond.py b/studio/backend/tests/fixtures/fake_lemond.pynew file mode 100644index 00000000000..b5b6c708949--- /dev/null+++ b/studio/backend/tests/fixtures/fake_lemond.py@@ -0,0 +1,215 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Fake lemond 11.9.0 with authenticated requests, model state and download progress.++Accepts LemonadeServer's arguments and logs requests to cache/requests.jsonl.+"""++from __future__ import annotations++import argparse+import json+import os+import signal+import sys+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++CATALOG = [+ {+ "id": "qwen3-0.6b-FLM",+ "checkpoint": "qwen3:0.6b",+ "labels": ["reasoning", "chat"],+ "size": 0.66,+ "max_context_window": 40960,+ },+ {+ "id": "qwen3-it-4b-FLM",+ "checkpoint": "qwen3-it:4b",+ "labels": ["tool-calling", "chat"],+ "size": 3.1,+ "max_context_window": 40960,+ },+ {+ "id": "gemma3-4b-FLM",+ "checkpoint": "gemma3:4b",+ "labels": ["vision", "chat"],+ "size": 4.5,+ "max_context_window": 131072,+ },+ {+ "id": "embed-gemma-300m-FLM",+ "checkpoint": "embed-gemma:300m",+ "labels": ["embeddings"],+ "size": 0.62,+ },+ {+ "id": "Qwen3-0.6B-GGUF",+ "checkpoint": "unsloth/Qwen3-0.6B-GGUF:Q4_0",+ "labels": ["chat"],+ "recipe": "llamacpp",+ },+]+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("cache_dir")+ parser.add_argument("config_dir")+ parser.add_argument("--port", type = int, required = True)+ parser.add_argument("--host", default = "127.0.0.1")+ parser.add_argument("--no-broadcast", action = "store_true")+ parser.add_argument("--log-file", default = "auto")+ args = parser.parse_args()++ if os.environ.get("FAKE_LEMOND_IGNORE_SIGTERM") == "1":+ # A lemond that never acts on SIGTERM, so only a SIGKILL death signal ends it.+ signal.signal(signal.SIGTERM, signal.SIG_IGN)+ key = os.environ.get("LEMONADE_API_KEY", "")+ cache = Path(args.cache_dir)+ record = cache / "requests.jsonl"+ downloaded = set(json.loads(os.environ.get("FAKE_LEMOND_DOWNLOADED", "[]")))+ loaded: dict[str, dict] = {}++ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *a) -> None:+ return++ def _send(self, status: int, body) -> None:+ data = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def _authorized(self) -> bool:+ if self.path == "/live":+ return True+ if self.headers.get("Authorization") != f"Bearer {key}":+ self._send(401, {"error": "Invalid or missing API key"})+ return False+ return True++ def _body(self) -> dict:+ length = int(self.headers.get("Content-Length") or 0)+ body = json.loads(self.rfile.read(length) or b"{}") if length else {}+ with open(record, "a", encoding = "utf-8") as handle:+ handle.write(json.dumps({"path": self.path, "body": body}) + "\n")+ return body++ def do_GET(self) -> None: # noqa: N802+ if not self._authorized():+ return+ if self.path == "/live":+ self._send(200, {"status": "ok"})+ elif self.path == "/v1/health":+ self._send(+ 200,+ {+ "status": "ok",+ "all_models_loaded": [+ {+ "model_name": name,+ "device": "npu",+ "loaded": True,+ "recipe": "flm",+ "recipe_options": options,+ }+ for name, options in loaded.items()+ ],+ },+ )+ elif self.path.startswith("/v1/models"):+ if os.environ.get("FAKE_LEMOND_MODELS_FAILS") == "1":+ self._send(200, {"status": "error", "message": "catalog unavailable"})+ return+ self._send(+ 200,+ {+ "data": [+ {"recipe": "flm", **row, "downloaded": row["id"] in downloaded}+ for row in CATALOG+ ]+ },+ )+ else:+ self._send(404, {"error": "not found"})++ def do_POST(self) -> None: # noqa: N802+ if not self._authorized():+ return+ body = self._body()+ name = body.get("model_name")+ if self.path == "/v1/install":+ time.sleep(float(os.environ.get("FAKE_LEMOND_INSTALL_SECONDS", "0")))+ flm = cache / "bin" / "flm" / "npu" / "flm"+ flm.parent.mkdir(parents = True, exist_ok = True)+ report = os.environ.get("FAKE_FLM_VALIDATE", '{"ready": true}')+ pause = os.environ.get("FAKE_FLM_VALIDATE_SECONDS", "0")+ flm.write_text(f"#!/bin/sh\nsleep {pause}\necho '{report}'\n", encoding = "utf-8")+ flm.chmod(0o755)+ self._send(200, {"status": "success", "recipe": "flm", "backend": "npu"})+ elif self.path == "/v1/pull":+ pull = os.environ.get("FAKE_LEMOND_PULL")+ if pull == "error":+ self._send(200, {"status": "error", "message": "disk full"})+ return+ progress = 'data: {"file":"model.q4nx","file_index":2,"total_files":4,"percent":40,"bytes_downloaded":4,"bytes_total":10}\n\n'+ if pull == "truncated":+ events = progress.encode()+ else:+ downloaded.add(name)+ events = (+ progress + "event: complete\n"+ 'data: {"file":"","file_index":4,"total_files":4,"percent":100}\n\n'+ ).encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(events)))+ self.end_headers()+ self.wfile.write(events)+ elif self.path == "/v1/load":+ time.sleep(float(os.environ.get("FAKE_LEMOND_LOAD_SECONDS", "0")))+ if name not in downloaded:+ self._send(404, {"error": {"message": f"Model '{name}' was not found."}})+ return+ if name == os.environ.get("FAKE_LEMOND_LOAD_FAILS_FOR"):+ self._send(500, {"error": {"message": "flm failed to start"}})+ return+ loaded.clear()+ loaded[name] = {"ctx_size": body.get("ctx_size"), "flm_args": ""}+ self._send(200, {"status": "success", "model_name": name, "recipe": "flm"})+ elif self.path == "/v1/unload":+ failure = os.environ.get("FAKE_LEMOND_UNLOAD_FAILS")+ if failure == "1":+ self._send(500, {"error": {"message": "unload failed"}})+ return+ if failure == "200":+ self._send(200, {"status": "error", "message": "unload failed"})+ return+ if name:+ loaded.pop(name, None)+ else:+ loaded.clear()+ self._send(200, {"status": "success"})+ elif self.path == "/v1/delete":+ if os.environ.get("FAKE_LEMOND_DELETE_FAILS") == "1":+ self._send(200, {"status": "error", "message": "file in use"})+ return+ downloaded.discard(name)+ self._send(200, {"status": "success", "message": f"Deleted model: {name}"})+ else:+ self._send(404, {"error": "not found"})++ server = ThreadingHTTPServer((args.host, args.port), Handler)+ print(f"fake lemond listening on {args.port}", flush = True)+ server.serve_forever()+++if __name__ == "__main__":+ sys.exit(main())diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.pyindex 5e3de85cc13..cfeb7a426c1 100644--- a/studio/backend/tests/multi_account/factories_media.py+++ b/studio/backend/tests/multi_account/factories_media.py@@ -351,9 +351,16 @@ FACTORIES = {"routes.inference:HEAD:/sandbox/{session_id}/{filename:path}": Factory("media-sandbox"),}+_NPU_INSTALLATION_MODEL = (+ "an NPU model id names FastFlowLM's one per-installation model store, not an account's "+ "object, and the route is owner-only (policy.require_owner), so no account owns it"+)+SKIPPED = {"routes.inference:POST:/sandbox/{session_id}/reveal": ("opens the backend host's file manager, so a success spawns xdg-open on a machine with ""no desktop session and the only in-process outcome is the 500 that failure maps to"),+ "routes.npu:DELETE:/models/{model_id}": _NPU_INSTALLATION_MODEL,+ "routes.npu:POST:/models/{model_id}/download": _NPU_INSTALLATION_MODEL,}diff --git a/studio/backend/tests/test_control_markup_neutralize_7066.py b/studio/backend/tests/test_control_markup_neutralize_7066.pyindex c0af25c0a22..dcc1b6bdf83 100644--- a/studio/backend/tests/test_control_markup_neutralize_7066.py+++ b/studio/backend/tests/test_control_markup_neutralize_7066.py@@ -2819,10 +2819,11 @@ def test_media_payload_in_a_tool_result_is_swept():def test_custom_provider_is_treated_as_template_applying():"""A "custom" provider is a user-supplied OpenAI-compatible base_url(routes/providers.py:207-213), which is how a self-hosted vLLM or llama.cpp is- registered without its preset, so it has to be swept like the named ones (#7066)."""+ registered without its preset, so it has to be swept like the named ones (#7066). The+ NPU's lemond serves FastFlowLM, which applies the model's own template as well."""from core.inference.external_provider import _TEMPLATE_APPLYING_PROVIDERS- assert _TEMPLATE_APPLYING_PROVIDERS == {"vllm", "llama_cpp", "ollama", "custom"}+ assert _TEMPLATE_APPLYING_PROVIDERS == {"vllm", "llama_cpp", "ollama", "custom", "lemonade"}providers = (_REPO_ROOT / "studio" / "backend" / "routes" / "providers.py").read_text(encoding = "utf-8")diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex 5dccb80ddef..2c0a03604ab 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -819,6 +819,8 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):preview_module.router = APIRouter()whisper_module = ModuleType("routes.whisper")whisper_module.router = APIRouter()+ npu_module = ModuleType("routes.npu")+ npu_module.router = APIRouter()profile_stats_module = ModuleType("routes.profile_stats")profile_stats_module.router = APIRouter()accounts_module = ModuleType("routes.accounts")@@ -844,6 +846,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):monkeypatch.setitem(sys.modules, "routes.prompts", prompts_module)monkeypatch.setitem(sys.modules, "routes.preview", preview_module)monkeypatch.setitem(sys.modules, "routes.whisper", whisper_module)+ monkeypatch.setitem(sys.modules, "routes.npu", npu_module)monkeypatch.setitem(sys.modules, "routes.profile_stats", profile_stats_module)monkeypatch.setitem(sys.modules, "routes.accounts", accounts_module)diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex e7b3a3ecc26..6b860d51ce2 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -1052,6 +1052,7 @@ class TestLoadHubDownloadExclusion:"requested_parallel_slots","parallel_slots","is_mlx",+ "is_npu","mlx_kv_bits","mlx_kv_bits_requested","mlx_kv_quant_eligibility",diff --git a/studio/backend/tests/test_native_context_length.py b/studio/backend/tests/test_native_context_length.pyindex e24cfc68a5c..069d451e8f0 100644--- a/studio/backend/tests/test_native_context_length.py+++ b/studio/backend/tests/test_native_context_length.py@@ -431,13 +431,22 @@ class TestRouteCompleteness:block that leaves them off now defaults them to None and blanks the control."""blocks = self._find_construction_blocks("LoadResponse")- non_gguf = [b for b in blocks if "is_gguf = True" not in b and "is_gguf=True" not in b]+ npu = [b for b in blocks if "is_npu = True" in b]+ non_gguf = [+ b+ for b in blocks+ if "is_gguf = True" not in b and "is_gguf=True" not in b and b not in npu+ ]assert non_gguf, "Expected at least one non-GGUF LoadResponse block"for block in non_gguf:for field in ("native_context_length", "max_context_length"):assert re.search(rf"{field} = _positive_int_or_none\(\s*_model_info\.get\(", block), f"Non-GGUF LoadResponse should read {field} from _model_info:\n{block[:200]}"+ assert npu, "Expected the NPU LoadResponse block"+ for block in npu:+ for field in ("native_context_length", "max_context_length"):+ assert f"{field} = model.max_context_length" in block, block[:200]def test_non_gguf_load_responses_set_runtime_context_length(self):"""Non-GGUF LoadResponse blocks report runtime context_length."""diff --git a/studio/backend/tests/test_npu_backend.py b/studio/backend/tests/test_npu_backend.pynew file mode 100644index 00000000000..5d75a5ea2d9--- /dev/null+++ b/studio/backend/tests/test_npu_backend.py@@ -0,0 +1,590 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exercise NPU lifecycle and API calls against a fake lemond child process.++POSIX only: the stub executable is a shell script.+"""++from __future__ import annotations++import json+import os+import sys+import textwrap+import time+from pathlib import Path++import pytest++from core.inference import npu_backend as nb+from core.inference.lemonade_server import LemonadeServer, LemonadeUnavailable++pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "shell-script lemond stand-in")++_FAKE = Path(__file__).parent / "fixtures" / "fake_lemond.py"+++def _binary(tmp_path: Path) -> Path:+ binary = tmp_path / "bin" / "lemond"+ binary.parent.mkdir(parents = True)+ binary.write_text(+ textwrap.dedent(+ f"""\+ #!/bin/sh+ exec "{sys.executable}" "{_FAKE}" "$@"+ """+ ),+ encoding = "utf-8",+ )+ binary.chmod(0o755)+ return binary+++class _Installer:+ def __init__(self, binary: Path) -> None:+ self.binary = binary+ self.installs = 0++ def installed_lemond(self, root):+ return self.binary++ def install(+ self,+ root,+ cancel = None,+ ):+ self.installs += 1+ return self.binary+++def npu(tmp_path, monkeypatch):+ installer = _Installer(_binary(tmp_path))+ monkeypatch.setattr(nb, "_installer_module", lambda: installer)+ monkeypatch.setattr(+ nb,+ "detect_amd_npu",+ lambda: {"present": True, "supported": True, "family": "XDNA2", "name": "NPU Strix Halo"},+ )+ backend = nb.LemonadeNpuBackend(root = tmp_path / "lemonade")+ backend.installer = installer+ yield backend+ backend.shutdown()+++def _requests(backend) -> list[dict]:+ path = backend.root / "cache" / "requests.jsonl"+ if not path.exists():+ return []+ return [json.loads(line) for line in path.read_text().splitlines()]+++def _wait_until(condition, tries: int = 300) -> None:+ """Poll a condition a test thread brings about. Counts polls: no clock in the assertion."""+ for _ in range(tries):+ if condition():+ return+ time.sleep(0.05)+ pytest.fail("the condition never held")+++def _returns_promptly(call, within: float = 30.0) -> None:+ """Run ``call`` on a thread and require it back well inside the 60 s stall it must cut short."""+ import threading++ thread = threading.Thread(target = call, daemon = True)+ thread.start()+ thread.join(timeout = within)+ assert not thread.is_alive(), f"{call} waited out the stall"+++def test_enable_installs_starts_and_validates(npu):+ status = npu.enable()+ assert status["state"] == "ready"+ assert status["runtime_running"] is True+ assert status["validation"]["ready"] is True+ assert npu.installer.installs == 1+ assert [r["body"] for r in _requests(npu) if r["path"] == "/v1/install"] == [+ {"recipe": "flm", "backend": "npu", "stream": False}+ ]+++def test_config_is_private_and_quiet(npu):+ npu.enable()+ config = json.loads((npu.root / "config" / "config.json").read_text())+ assert config["broadcast"] is False+ assert config["auto_check_model_updates"] is False+ assert config["host"] == "127.0.0.1"+ # Not "auto", which scans the user's Hugging Face cache for GGUFs.+ assert config["models_dir"] == str(npu.root / "cache" / "models")+ assert config["flm"]["prefer_system"] is False+++def test_validation_failure_names_the_fix(npu, monkeypatch):+ monkeypatch.setenv(+ "FAKE_FLM_VALIDATE", '{"ready": false, "memlock_ok": false, "all_fw_ok": true}'+ )+ with pytest.raises(nb.NpuError, match = "locked-memory limit"):+ npu.enable()+ status = npu.status()+ assert status["state"] == "failed"+ assert "memlock" in status["error"]+++def test_unsupported_npu_is_refused_before_any_download(tmp_path, monkeypatch):+ installer = _Installer(_binary(tmp_path))+ monkeypatch.setattr(nb, "_installer_module", lambda: installer)+ monkeypatch.setattr(+ nb, "detect_amd_npu", lambda: {"present": True, "supported": False, "family": "XDNA1"}+ )+ backend = nb.LemonadeNpuBackend(root = tmp_path / "lemonade")+ with pytest.raises(nb.NpuError, match = "XDNA 2"):+ backend.enable()+ assert installer.installs == 0+++def test_catalog_keeps_flm_chat_models_only(npu):+ npu.enable()+ ids = [model.id for model in npu.catalog()]+ assert ids == sorted(["gemma3-4b-FLM", "qwen3-0.6b-FLM", "qwen3-it-4b-FLM"])+ by_id = {model.id: model for model in npu.catalog()}+ assert by_id["gemma3-4b-FLM"].vision and not by_id["gemma3-4b-FLM"].tools+ assert by_id["qwen3-it-4b-FLM"].tools+ assert by_id["qwen3-0.6b-FLM"].reasoning+ assert by_id["qwen3-0.6b-FLM"].model_path == "lemonade:qwen3-0.6b-FLM"+++def test_download_relays_progress_then_completes(npu):+ npu.enable()+ events = list(npu.download("qwen3-0.6b-FLM"))+ assert events[0]["percent"] == 40+ assert events[-1]["event"] == "complete"+ assert {m.id: m.downloaded for m in npu.catalog()}["qwen3-0.6b-FLM"] is True+++ "pull, message", [("truncated", "ended before it completed"), ("error", "disk full")]+)+def test_a_download_without_lemonds_complete_event_fails(npu, monkeypatch, pull, message):+ monkeypatch.setenv("FAKE_LEMOND_PULL", pull)+ npu.enable()+ with pytest.raises(nb.NpuError, match = message):+ list(npu.download("qwen3-0.6b-FLM"))+ assert {m.id: m.downloaded for m in npu.catalog()}["qwen3-0.6b-FLM"] is False+++def test_the_validator_is_tracked_while_it_runs(npu, monkeypatch):+ adopted: list[int] = []+ forgotten: list[int] = []+ monkeypatch.setattr(nb, "adopt_pid", adopted.append)+ monkeypatch.setattr(nb, "forget_pid", forgotten.append)+ npu.enable()+ assert len(adopted) == 1 and forgotten == adopted+++def test_load_requires_a_download(npu):+ npu.enable()+ with pytest.raises(nb.NpuError, match = "not downloaded"):+ npu.load("qwen3-0.6b-FLM")+ assert not npu.is_loaded+++def test_load_reports_the_context_lemond_started_with(npu, monkeypatch):+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ npu.load("qwen3-0.6b-FLM")+ assert npu.is_loaded+ # Not the model's 40960 maximum: an unset length loads at the default.+ assert npu.loaded_context_length == nb.DEFAULT_CONTEXT_LENGTH+ load = [r["body"] for r in _requests(npu) if r["path"] == "/v1/load"][-1]+ assert load == {"model_name": "qwen3-0.6b-FLM", "ctx_size": 8192, "save_options": False}++ npu.load("qwen3-0.6b-FLM", 100_000)+ assert npu.loaded_context_length == 40960+ upstream = npu.upstream()+ assert upstream.model == "qwen3-0.6b-FLM"+ assert upstream.public_model == "lemonade:qwen3-0.6b-FLM"+ assert upstream.base_url.startswith("http://127.0.0.1:")+ assert upstream.api_key+++def test_the_resident_reports_what_its_load_asked_for(npu):+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ npu.load("qwen3-0.6b-FLM")+ assert npu.resident().context_length == nb.DEFAULT_CONTEXT_LENGTH+ assert npu.resident().requested_context_length is None+ npu.load("qwen3-0.6b-FLM", 16384)+ assert npu.resident().requested_context_length == 16384+++def test_a_reader_racing_an_unload_does_not_crash(npu):+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ npu.load("qwen3-0.6b-FLM")+ server = npu._server+ alive = server.is_alive++ def _unloaded_meanwhile():+ # unload() clears the record between a reader's liveness check and its read.+ npu._loaded = None+ return alive()++ server.is_alive = _unloaded_meanwhile+ try:+ assert npu.loaded_model.id == "qwen3-0.6b-FLM"+ assert npu.loaded_model is None+ finally:+ del server.is_alive+++def test_a_catalog_error_body_is_an_error_not_an_empty_catalog(npu, monkeypatch):+ monkeypatch.setenv("FAKE_LEMOND_MODELS_FAILS", "1")+ npu.enable()+ with pytest.raises(nb.NpuError, match = "catalog unavailable"):+ npu.catalog()+++def test_unload_then_delete(npu):+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ npu.load("qwen3-0.6b-FLM")+ with pytest.raises(nb.NpuError, match = "Unload"):+ npu.delete("qwen3-0.6b-FLM")+ assert npu.unload() == "lemonade:qwen3-0.6b-FLM"+ assert not npu.is_loaded+ assert npu.unload() is None+ npu.delete("qwen3-0.6b-FLM")+ assert {m.id: m.downloaded for m in npu.catalog()}["qwen3-0.6b-FLM"] is False++[email protected]("failure", ["1", "200"])+def test_a_rejected_unload_stops_lemond(npu, monkeypatch, failure):+ # "200": lemond's HTTP 200 answer with an error body.+ monkeypatch.setenv("FAKE_LEMOND_UNLOAD_FAILS", failure)+ monkeypatch.setenv("FAKE_LEMOND_DOWNLOADED", '["qwen3-0.6b-FLM"]')+ npu.enable()+ npu.load("qwen3-0.6b-FLM")+ process = npu._server._process+ assert npu.unload() == "lemonade:qwen3-0.6b-FLM"+ assert process.poll() is not None+ assert not npu.is_loaded+ npu.load("qwen3-0.6b-FLM")+ assert npu.is_loaded++[email protected]("stop", ["cancel_load", "shutdown"])+def test_a_slow_load_can_be_stopped(npu, monkeypatch, stop):+ import threading++ monkeypatch.setenv("FAKE_LEMOND_LOAD_SECONDS", "60")+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ errors: list[BaseException] = []++ def _load():+ try:+ npu.load("qwen3-0.6b-FLM")+ except BaseException as exc: # noqa: BLE001+ errors.append(exc)++ thread = threading.Thread(target = _load)+ thread.start()+ _wait_until(lambda: any(r["path"] == "/v1/load" for r in _requests(npu)))+ assert npu.cancel_load("other-FLM") is False+ if stop == "cancel_load":+ _returns_promptly(lambda: npu.cancel_load("qwen3-0.6b-FLM"))+ else:+ _returns_promptly(npu.shutdown)+ thread.join(timeout = 30)+ assert not thread.is_alive()+ assert len(errors) == 1 and isinstance(errors[0], nb.NpuLoadCancelled)+ assert not npu.is_loaded+ assert npu.loading_model is None++[email protected]("phase", ["download", "installing_flm", "validating"])+def test_shutdown_does_not_wait_for_enable(npu, monkeypatch, phase):+ import threading++ if phase == "download":+ original = npu.installer.install++ def _slow_download(root, cancel = None):+ assert cancel is not None and cancel.wait(60)+ raise RuntimeError("Lemonade download cancelled.")++ npu.installer.install = _slow_download+ elif phase == "installing_flm":+ monkeypatch.setenv("FAKE_LEMOND_INSTALL_SECONDS", "60")+ else:+ monkeypatch.setenv("FAKE_FLM_VALIDATE_SECONDS", "60")+ errors: list[BaseException] = []++ def _enable():+ try:+ npu.enable()+ except BaseException as exc: # noqa: BLE001+ errors.append(exc)++ thread = threading.Thread(target = _enable)+ thread.start()+ target = "installing" if phase == "download" else phase+ _wait_until(+ lambda: npu.status()["state"] == target+ and (phase != "validating" or npu._validate_process is not None)+ )+ _returns_promptly(npu.shutdown)+ thread.join(timeout = 30)+ assert not thread.is_alive()+ assert len(errors) == 1 and isinstance(errors[0], nb.NpuError)+ assert npu.status()["runtime_running"] is False+ assert npu.status()["ready"] is False+ if phase == "download":+ npu.installer.install = original+++def test_readiness_survives_a_restart_only_after_validation(npu, monkeypatch):+ npu.enable()+ assert npu.status()["ready"] is True+ npu.shutdown()+ restarted = nb.LemonadeNpuBackend(root = npu.root)+ assert restarted.status()["state"] == "idle"+ assert restarted.status()["ready"] is True++ monkeypatch.setenv("FAKE_FLM_VALIDATE", '{"ready": false, "memlock_ok": false}')+ with pytest.raises(nb.NpuError):+ restarted.enable()+ restarted.shutdown()+ assert nb.LemonadeNpuBackend(root = npu.root).status()["ready"] is False+++def test_a_failed_replacement_leaves_nothing_on_the_npu(npu, monkeypatch):+ monkeypatch.setenv("FAKE_LEMOND_DOWNLOADED", '["qwen3-0.6b-FLM", "gemma3-4b-FLM"]')+ monkeypatch.setenv("FAKE_LEMOND_LOAD_FAILS_FOR", "gemma3-4b-FLM")+ npu.enable()+ npu.load("qwen3-0.6b-FLM")+ process = npu._server._process+ with pytest.raises(nb.NpuError, match = "flm failed to start"):+ npu.load("gemma3-4b-FLM")+ assert not npu.is_loaded+ assert process.poll() is not None+ npu.load("qwen3-0.6b-FLM")+ assert npu.is_loaded+++def test_a_load_refused_before_touching_the_npu_keeps_the_resident(npu):+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ npu.load("qwen3-0.6b-FLM")+ with pytest.raises(nb.NpuError, match = "not downloaded"):+ npu.load("gemma3-4b-FLM")+ assert npu.loaded_model.id == "qwen3-0.6b-FLM"+++def test_a_cancel_during_the_final_health_check_wins(npu, monkeypatch):+ # The cancel stops lemond; the download must outlive the restart, as files on disk do.+ monkeypatch.setenv("FAKE_LEMOND_DOWNLOADED", '["qwen3-0.6b-FLM"]')+ npu.enable()+ resident_context = npu._resident_context++ def _cancelled_meanwhile(server, model_id):+ ctx = resident_context(server, model_id)+ assert npu.cancel_load(model_id) is True+ return ctx++ npu._resident_context = _cancelled_meanwhile+ with pytest.raises(nb.NpuLoadCancelled):+ npu.load("qwen3-0.6b-FLM")+ assert npu._loaded is None+ assert npu.loading_model is None+ del npu._resident_context+ npu.load("qwen3-0.6b-FLM")+ assert npu.cancel_load("qwen3-0.6b-FLM") is False+ assert npu.is_loaded+++def test_a_cancel_landing_as_the_load_starts_is_kept(npu, monkeypatch):+ import threading++ monkeypatch.setenv("FAKE_LEMOND_DOWNLOADED", '["qwen3-0.6b-FLM"]')+ npu.enable()+ event = npu._load_cancelled+ results: list[bool] = []++ class _CancelledAsTheLoadStarts:+ def clear(self):+ # A cancel from another thread lands while the load is publishing itself.+ thread = threading.Thread(+ target = lambda: results.append(npu.cancel_load("qwen3-0.6b-FLM"))+ )+ thread.start()+ thread.join(timeout = 0.5)+ event.clear()++ def __getattr__(self, name):+ return getattr(event, name)++ npu._load_cancelled = _CancelledAsTheLoadStarts()+ with pytest.raises(nb.NpuLoadCancelled):+ npu.load("qwen3-0.6b-FLM")+ assert results == [True]+ assert npu._loaded is None+++def test_a_refused_delete_is_reported(npu, monkeypatch):+ monkeypatch.setenv("FAKE_LEMOND_DELETE_FAILS", "1")+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ with pytest.raises(nb.NpuError, match = "file in use"):+ npu.delete("qwen3-0.6b-FLM")+ assert {m.id: m.downloaded for m in npu.catalog()}["qwen3-0.6b-FLM"] is True+++def test_a_restarted_runtime_reports_nothing_loaded(npu):+ npu.enable()+ list(npu.download("qwen3-0.6b-FLM"))+ npu.load("qwen3-0.6b-FLM")+ npu._server._process.kill()+ npu._server._process.wait()+ assert not npu.is_loaded+ assert npu.catalog()+ assert npu.status()["loaded_model"] is None+++def test_requests_without_the_key_are_refused(npu):+ import httpx++ npu.enable()+ base = npu._server.base_url+ assert httpx.get(f"{base}/v1/health", trust_env = False).status_code == 401+ assert httpx.get(f"{base}/live", trust_env = False).status_code == 200+++def test_stop_ends_the_process(npu):+ npu.enable()+ process = npu._server._process+ npu.shutdown()+ assert process.poll() is not None+ assert npu.status()["runtime_running"] is False++[email protected](not sys.platform.startswith("linux"), reason = "PR_SET_PDEATHSIG is Linux")+def test_lemond_dies_with_a_killed_owner_even_if_it_ignores_sigterm(tmp_path):+ """A SIGKILLed Unsloth must not leave lemond (and the model FastFlowLM holds) behind.++ The death signal is SIGKILL, not SIGTERM: this lemond ignores SIGTERM outright, and the real one+ took about 9 s over it with a model loaded."""+ import signal+ import subprocess+ import time++ binary = _binary(tmp_path)+ owner_src = textwrap.dedent(+ f"""\+ import sys, time+ from pathlib import Path+ sys.path.insert(0, {str(Path(__file__).resolve().parents[1])!r})+ from core.inference.lemonade_server import LemonadeServer+ root = Path({str(tmp_path)!r})+ server = LemonadeServer(+ Path({str(binary)!r}),+ cache_dir = root / "cache",+ config_dir = root / "config",+ flm_model_dir = root / "flm",+ )+ server.start(timeout = 30)+ print(server.pid, flush = True)+ time.sleep(600)+ """+ )+ env = dict(os.environ, FAKE_LEMOND_IGNORE_SIGTERM = "1")+ owner = subprocess.Popen(+ [sys.executable, "-c", owner_src], stdout = subprocess.PIPE, text = True, env = env+ )+ try:+ lemond_pid = int(owner.stdout.readline())+ owner.send_signal(signal.SIGKILL)+ owner.wait(timeout = 10)+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ try:+ os.kill(lemond_pid, 0)+ except ProcessLookupError:+ break+ time.sleep(0.1)+ else:+ os.kill(lemond_pid, signal.SIGKILL)+ pytest.fail("lemond outlived its SIGKILLed owner")+ finally:+ if owner.poll() is None:+ owner.kill()+++def test_a_server_that_never_answers_is_reported(tmp_path):+ binary = tmp_path / "lemond"+ binary.write_text("#!/bin/sh\necho 'bind failed'\nexit 3\n", encoding = "utf-8")+ binary.chmod(0o755)+ server = LemonadeServer(+ binary,+ cache_dir = tmp_path / "cache",+ config_dir = tmp_path / "config",+ flm_model_dir = tmp_path / "flm",+ )+ with pytest.raises(LemonadeUnavailable, match = "bind failed"):+ server.start(timeout = 10)+ assert not server.is_alive()+++def test_stop_interrupts_a_start_that_never_becomes_ready(tmp_path):+ import threading++ binary = tmp_path / "lemond"+ binary.write_text("#!/bin/sh\nexec sleep 60\n", encoding = "utf-8")+ binary.chmod(0o755)+ server = LemonadeServer(+ binary,+ cache_dir = tmp_path / "cache",+ config_dir = tmp_path / "config",+ flm_model_dir = tmp_path / "flm",+ )+ errors: list[BaseException] = []++ def _start():+ try:+ server.start(timeout = 60)+ except BaseException as exc: # noqa: BLE001+ errors.append(exc)++ thread = threading.Thread(target = _start)+ thread.start()+ _wait_until(server.is_alive)+ _returns_promptly(server.stop)+ thread.join(timeout = 30)+ assert len(errors) == 1 and isinstance(errors[0], LemonadeUnavailable)+ assert not server.is_alive()+ server.close()+++ "path, expected",+ [+ ("lemonade:qwen3-0.6b-FLM", "qwen3-0.6b-FLM"),+ ("lemonade: gemma3-4b-FLM ", "gemma3-4b-FLM"),+ ],+)+def test_model_id_from_path(path, expected):+ assert nb.is_npu_model_path(path)+ assert nb.model_id_from_path(path) == expected++[email protected]("path", ["lemonade:", "lemonade:../x", "lemonade:a/b"])+def test_model_id_from_path_rejects_non_ids(path):+ with pytest.raises(nb.NpuError):+ nb.model_id_from_path(path)+++def test_other_model_paths_are_not_npu():+ assert not nb.is_npu_model_path("unsloth/Qwen3-0.6B-GGUF")+ assert not nb.is_npu_model_path(None)diff --git a/studio/backend/tests/test_npu_chat_route.py b/studio/backend/tests/test_npu_chat_route.pynew file mode 100644index 00000000000..8d6173acd95--- /dev/null+++ b/studio/backend/tests/test_npu_chat_route.py@@ -0,0 +1,1091 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Test NPU chat through the route and proxy against a local HTTP server.++Replay FastFlowLM 1.0.3 stream shapes and record outgoing request bodies.+"""++from __future__ import annotations++import asyncio+import json+import socket+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import httpx+import pytest+from fastapi import HTTPException++from core.inference import external_provider as ep_mod+from core.inference import npu_backend as nb+from core.inference.external_provider import _apply_fastflowlm_reasoning_controls+from models.inference import ChatCompletionRequest+++def _chunk(+ delta: dict,+ finish = None,+ usage = None,+) -> str:+ body = {+ "id": "chatcmpl-flm",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "qwen3:0.6b",+ "choices": [{"index": 0, "delta": {"role": "assistant", **delta}, "finish_reason": finish}],+ }+ if usage:+ body["usage"] = usage+ return "data: " + json.dumps(body) + "\n\n"+++_USAGE = {"prompt_tokens": 12, "completion_tokens": 5, "total_tokens": 17}+++def _script(prompt: str) -> str:+ if "FAULT" in prompt:+ return (+ _chunk({"content": "par"})+ + '{"error":"qds_device::wait() unexpected command state"}\n'+ + "data: [DONE]\n\n"+ )+ if "CUT" in prompt:+ return _chunk({"content": "par"}) + "data: [DONE]\n\n"+ if "TOOL" in prompt:+ call = {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "get_weather", "arguments": '{"city":"Paris"}'},+ }+ return (+ _chunk({"tool_calls": [call]}) + _chunk({}, "tool_calls", _USAGE) + "data: [DONE]\n\n"+ )+ if "FINAL" in prompt:+ return (+ _chunk({"content": "hello E"})+ + _chunk({"content": "ND hidden"}, "stop", _USAGE)+ + "data: [DONE]\n\n"+ )+ if "THINK" in prompt:+ return (+ _chunk({"reasoning_content": "Let me add."})+ + _chunk({"content": "4"})+ + _chunk({}, "stop", _USAGE)+ + "data: [DONE]\n\n"+ )+ words = ["one", " two", " sev", "en", " eight"]+ return (+ ": ping\n\n"+ + "".join(_chunk({"content": w}) for w in words)+ + _chunk({}, "length", _USAGE)+ + "data: [DONE]\n\n"+ )+++class _Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *args) -> None:+ return++ def do_POST(self) -> None: # noqa: N802+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))+ self.server.recorded.append(+ {"body": body, "auth": self.headers.get("Authorization"), "path": self.path}+ )+ prompt = json.dumps(body.get("messages"))+ if "SLOW" in prompt:+ time.sleep(20)+ data = _script(prompt).encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)+++class _FakeNpu:+ def __init__(self, upstream) -> None:+ self._upstream = upstream+ self.is_loaded = True++ def upstream(self):+ return self._upstream+++def flm(monkeypatch):+ httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ httpd.daemon_threads = True+ httpd.recorded = []+ thread = threading.Thread(target = httpd.serve_forever, daemon = True)+ thread.start()++ def install(**caps):+ upstream = nb.ManagedUpstream(+ provider_type = "lemonade",+ base_url = f"http://127.0.0.1:{httpd.server_address[1]}/v1",+ api_key = "secret-key",+ model = "qwen3-0.6b-FLM",+ public_model = "lemonade:qwen3-0.6b-FLM",+ supports_vision = caps.get("vision", False),+ supports_tools = caps.get("tools", False),+ supports_reasoning = caps.get("reasoning", False),+ context_length = 8192,+ )+ monkeypatch.setattr(nb, "get_npu_backend", lambda: _FakeNpu(upstream))+ return httpd.recorded++ yield install+ httpd.shutdown()+ httpd.server_close()+ thread.join(timeout = 10)+++def _request():+ from starlette.requests import Request+ async def receive() -> dict:+ await asyncio.sleep(3600)+ return {"type": "http.disconnect"}++ return Request(+ {+ "type": "http",+ "http_version": "1.1",+ "method": "POST",+ "path": "/v1/chat/completions",+ "raw_path": b"/v1/chat/completions",+ "root_path": "",+ "scheme": "http",+ "query_string": b"",+ "headers": [(b"content-type", b"application/json")],+ "client": ("127.0.0.1", 12345),+ "server": ("127.0.0.1", 8000),+ },+ receive,+ )+++def _call(**fields):+ """Run the route; return (status, parsed body or SSE lines)."""+ import routes.inference as ri++ payload = ChatCompletionRequest(+ messages = fields.pop("messages", [{"role": "user", "content": "count"}]), **fields+ )+ out: dict = {}+ loop = asyncio.new_event_loop()+ previous = ep_mod._http_client, ep_mod._loopback_http_client+ client = httpx.AsyncClient()+ loopback = httpx.AsyncClient(trust_env = False)++ async def go() -> None:+ try:+ response = await ri._npu_chat_completions(payload, _request(), "tester")+ if hasattr(response, "body_iterator"):+ lines = []+ async for piece in response.body_iterator:+ text = piece.decode() if isinstance(piece, bytes) else piece+ lines.extend(line for line in text.split("\n") if line.strip())+ out["status"], out["body"] = response.status_code, lines+ else:+ out["status"], out["body"] = response.status_code, json.loads(response.body)+ finally:+ await client.aclose()+ await loopback.aclose()++ ep_mod._http_client, ep_mod._loopback_http_client = client, loopback+ try:+ loop.run_until_complete(go())+ finally:+ ep_mod._http_client, ep_mod._loopback_http_client = previous+ loop.close()+ return out["status"], out["body"]+++_TOOL = {"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}+++def _data(lines):+ return [+ json.loads(line[5:]) for line in lines if line.startswith("data:") and "[DONE]" not in line+ ]+++def test_an_environment_proxy_never_sees_npu_chat(flm, monkeypatch):+ seen = []+ proxy = socket.socket()+ proxy.bind(("127.0.0.1", 0))+ proxy.listen(4)+ proxy.settimeout(0.2)++ def serve() -> None:+ while not stop.is_set():+ try:+ conn, _ = proxy.accept()+ except OSError:+ continue+ seen.append(conn.recv(4096))+ conn.close()++ stop = threading.Event()+ thread = threading.Thread(target = serve, daemon = True)+ thread.start()+ # Studio started under a proxy: its shared client picks the proxy up at construction.+ monkeypatch.delenv("NO_PROXY", raising = False)+ monkeypatch.delenv("no_proxy", raising = False)+ monkeypatch.setenv("HTTP_PROXY", f"http://127.0.0.1:{proxy.getsockname()[1]}")+ try:+ recorded = flm()+ status, body = _call(stream = False)+ finally:+ stop.set()+ thread.join(timeout = 5)+ proxy.close()+ assert seen == []+ assert status == 200 and recorded[-1]["auth"] == "Bearer secret-key"++[email protected]("stream", [True, False])+def test_a_top_level_image_reaches_a_vision_model(flm, stream):+ import base64+ import io++ from PIL import Image++ buffer = io.BytesIO()+ Image.new("RGB", (4, 4), "red").save(buffer, format = "PNG")+ recorded = flm(vision = True)+ status, _ = _call(stream = stream, image_base64 = base64.b64encode(buffer.getvalue()).decode())+ assert status == 200+ last = recorded[-1]["body"]["messages"][-1]+ assert isinstance(last["content"], list)+ assert any(part.get("type") == "image_url" for part in last["content"])+++def test_the_body_fastflowlm_receives(flm):+ recorded = flm(reasoning = True)+ _call(stream = False, temperature = 0.3, min_p = 0.05)+ sent = recorded[-1]+ body = sent["body"]+ assert sent["auth"] == "Bearer secret-key"+ assert body["model"] == "qwen3-0.6b-FLM"+ assert body["stream"] is True+ assert body["think"] is True+ assert "chat_template_kwargs" not in body+ assert "min_p" not in body+ assert {"top_p", "top_k", "repetition_penalty", "temperature"} <= set(body)++[email protected]("stream", [True, False])+def test_custom_responses_selection_cannot_redirect_managed_npu(flm, stream):+ recorded = flm(reasoning = True)+ status, response = _call(+ stream = stream,+ provider_type = "custom",+ provider_api_type = "responses",+ provider_base_url = "http://127.0.0.1:1/v1",+ external_model = "wrong-model",+ )+ assert status == 200+ sent = recorded[-1]+ assert sent["path"] == "/v1/chat/completions"+ assert sent["auth"] == "Bearer secret-key"+ assert sent["body"]["model"] == "qwen3-0.6b-FLM"+ assert sent["body"]["stream"] is True+ assert sent["body"]["think"] is True+ assert "input" not in sent["body"]+ if stream:+ assert response[-1] == "data: [DONE]"+ else:+ assert response["choices"][0]["message"]["content"] == "one two seven eight"+++def test_thinking_off_and_non_reasoning_models(flm):+ recorded = flm(reasoning = True)+ _call(stream = False, enable_thinking = False)+ assert recorded[-1]["body"]["think"] is False+ recorded = flm(reasoning = False)+ _call(stream = False)+ assert recorded[-1]["body"]["think"] is False+++def test_non_streaming_reply_is_collected_from_the_stream(flm):+ flm()+ status, body = _call(stream = False)+ assert status == 200+ assert body["object"] == "chat.completion"+ assert body["model"] == "lemonade:qwen3-0.6b-FLM"+ choice = body["choices"][0]+ assert choice["message"]["content"] == "one two seven eight"+ # The stream's own reason: FastFlowLM's non-streaming reply says "stop" for a cutoff.+ assert choice["finish_reason"] == "length"+ assert body["usage"] == _USAGE+++def test_streaming_rewrites_the_model_name(flm):+ flm()+ status, lines = _call(stream = True)+ chunks = _data(lines)+ assert status == 200+ assert {chunk["model"] for chunk in chunks} == {"lemonade:qwen3-0.6b-FLM"}+ assert lines[-1] == "data: [DONE]"+ assert (+ "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks)+ == "one two seven eight"+ )++[email protected]("stream", [True, False])+def test_stop_is_enforced_across_chunks(flm, stream):+ flm()+ status, out = _call(stream = stream, stop = ["seven"])+ if stream:+ chunks = _data(out)+ text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks)+ assert text == "one two "+ assert chunks[-1]["choices"][0]["finish_reason"] == "stop"+ assert out[-1] == "data: [DONE]"+ else:+ assert out["choices"][0]["message"]["content"] == "one two "+ assert out["choices"][0]["finish_reason"] == "stop"+++def test_a_partial_stop_match_is_released(flm):+ flm()+ _, body = _call(stream = False, stop = ["seventy"])+ assert body["choices"][0]["message"]["content"] == "one two seven eight"++[email protected]("stream", [True, False])+ "stop, expected",+ [+ (["END"], "hello "),+ (["END hiddenness"], "hello END hidden"),+ ],+)+def test_stop_on_the_finishing_chunk(flm, stream, stop, expected):+ flm()+ messages = [{"role": "user", "content": "FINAL"}]+ _, out = _call(stream = stream, stop = stop, messages = messages)+ if stream:+ chunks = _data(out)+ text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks)+ finish = [+ c["choices"][0]["finish_reason"] for c in chunks if c["choices"][0]["finish_reason"]+ ]+ assert out[-1] == "data: [DONE]"+ else:+ text = out["choices"][0]["message"]["content"]+ finish = [out["choices"][0]["finish_reason"]]+ assert text == expected+ assert finish == ["stop"]+++def test_reasoning_is_kept_apart(flm):+ flm(reasoning = True)+ _, body = _call(stream = False, messages = [{"role": "user", "content": "THINK"}])+ message = body["choices"][0]["message"]+ assert message["reasoning_content"] == "Let me add."+ assert message["content"] == "4"+++def test_tool_calls_are_assembled(flm):+ flm(tools = True)+ tools = [+ {"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}}+ ]+ _, body = _call(stream = False, tools = tools, messages = [{"role": "user", "content": "TOOL"}])+ choice = body["choices"][0]+ assert choice["finish_reason"] == "tool_calls"+ assert choice["message"]["tool_calls"] == [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "get_weather", "arguments": '{"city":"Paris"}'},+ }+ ]+++def test_tool_choice_none_withholds_the_tools(flm):+ recorded = flm(tools = True)+ tools = [+ {"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}}+ ]+ _call(stream = False, tools = tools, tool_choice = "none")+ assert "tools" not in recorded[-1]["body"]+++def test_a_bare_error_line_becomes_an_error(flm):+ flm()+ status, body = _call(stream = False, messages = [{"role": "user", "content": "FAULT"}])+ assert status == 502+ assert "qds_device" in body["error"]["message"]+ status, lines = _call(stream = True, messages = [{"role": "user", "content": "FAULT"}])+ errors = [chunk for chunk in _data(lines) if "error" in chunk]+ assert errors and "qds_device" in errors[0]["error"]["message"]+++ "fields, message",+ [+ ({"response_format": {"type": "json_object"}}, "response_format"),+ ({"seed": 7}, "seed"),+ ({"frequency_penalty": 0.5}, "frequency_penalty"),+ ({"tools": [_TOOL], "tool_choice": "required"}, "tool_choice"),+ ({"tools": [_TOOL], "parallel_tool_calls": False}, "parallel_tool_calls"),+ (+ {"tools": [_TOOL], "tool_choice": {"type": "function", "function": {"name": "f"}}},+ "tool_choice",+ ),+ ({"logit_bias": {"42": -100}}, "logit_bias"),+ ({"logprobs": True}, "logprobs"),+ ({"top_logprobs": 3}, "logprobs"),+ ({"n": 2}, "n"),+ (+ {+ "tools": [+ {+ "type": "function",+ "function": {"name": "f", "parameters": {"type": "object"}},+ }+ ]+ },+ "tool calling",+ ),+ (+ {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this"},+ {+ "type": "image_url",+ "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="},+ },+ ],+ }+ ]+ },+ "does not read images",+ ),+ ],+)+def test_what_fastflowlm_would_drop_is_refused(flm, fields, message):+ recorded = flm()+ with pytest.raises(HTTPException) as caught:+ _call(stream = False, **fields)+ assert caught.value.status_code == 400+ assert message in json.dumps(caught.value.detail)+ assert recorded == []+++def test_a_saved_connection_cannot_name_the_managed_type():+ from core.inference.providers import get_connectable_provider_info, list_available_providers++ assert get_connectable_provider_info("lemonade") is None+ assert get_connectable_provider_info("vllm") is not None+ assert "lemonade" not in {+ p["provider_type"] for p in list_available_providers(include_hidden = True)+ }+++def test_a_request_cannot_route_to_the_managed_type():+ import routes.inference as ri++ payload = ChatCompletionRequest(+ provider_type = "lemonade",+ provider_base_url = "http://127.0.0.1:1/v1",+ messages = [{"role": "user", "content": "hi"}],+ stream = True,+ )+ loop = asyncio.new_event_loop()+ try:+ with pytest.raises(HTTPException) as caught:+ loop.run_until_complete(ri._proxy_to_external_provider(payload, _request(), "t"))+ finally:+ loop.close()+ assert caught.value.status_code == 400+ assert "Unknown provider type" in str(caught.value.detail)+++ "enable, effort, expected",+ [+ (None, None, {}),+ (True, None, {"think": True}),+ (False, None, {"think": False}),+ (None, "none", {"think": False}),+ (True, "high", {"think": True, "reasoning_effort": "high"}),+ (False, "high", {"think": False}),+ ],+)+def test_fastflowlm_reasoning_controls(enable, effort, expected):+ body: dict = {}+ _apply_fastflowlm_reasoning_controls(body, enable, effort)+ assert body == expected+++def test_stop_loading_an_npu_model_does_not_wait_for_the_load(monkeypatch):+ """/load holds the lifecycle gate for the whole /v1/load, so Stop loading must not queue on it."""+ from core.inference.llama_keepwarm import inference_lifecycle_gate+ from models.inference import UnloadRequest+ from routes import inference as routes++ cancelled: list[str] = []++ class _Loading:+ is_loaded = False++ def cancel_load(self, model_id):+ cancelled.append(model_id)+ return True++ monkeypatch.setattr(nb, "peek_npu_backend", lambda: _Loading())++ async def _run():+ async with inference_lifecycle_gate():+ return await asyncio.wait_for(+ routes._unload_model_impl(+ UnloadRequest(model_path = "lemonade:qwen3-0.6b-FLM"), "owner"+ ),+ timeout = 10,+ )++ response = asyncio.run(_run())+ assert response.status == "unloaded"+ assert cancelled == ["qwen3-0.6b-FLM"]+++def test_an_owner_npu_model_is_hidden_from_managed_accounts(monkeypatch):+ """An NPU load publishes the owner as the loader, as a GPU load does."""+ from auth import policy+ from hub.services.models import account_access+ from models.inference import LoadRequest, UnloadRequest+ from routes import inference as routes+ from utils.account_context import AccountContext, run_as++ bob = AccountContext("b" * 32, "bob")+ model = nb.NpuModel(+ id = "qwen3-0.6b-FLM",+ checkpoint = "qwen3:0.6b",+ size_gb = 0.66,+ downloaded = True,+ labels = ("reasoning", "chat"),+ max_context_length = 40960,+ )++ class _Npu:+ is_loaded = False+ loaded_model = None+ loaded_context_length = None+ unloads = 0++ def loadable_model(self, model_id):+ return model++ def resident(self):+ if not self.is_loaded:+ return None+ return nb.NpuResident(+ model = model,+ context_length = 8192,+ requested_context_length = None,+ base_url = "http://127.0.0.1:1",+ api_key = "key",+ )++ def load(self, model_id, ctx):+ self.is_loaded, self.loaded_model, self.loaded_context_length = True, model, 8192++ def unload(self):+ self.unloads += 1++ def cancel_load(self, model_id):+ return False++ npu = _Npu()+ monkeypatch.setattr(nb, "get_npu_backend", lambda: npu)+ monkeypatch.setattr(nb, "peek_npu_backend", lambda: npu)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(account_access, "_resident_accounts", {})+ monkeypatch.setattr(account_access, "_resident_sharers", {})+ monkeypatch.setattr(routes, "_peek_inference_backend", lambda: None)+ monkeypatch.setattr(routes, "release_chat_gpu_claim", lambda: True)++ async def _nothing_loaded(_backend):+ return None++ monkeypatch.setattr(routes, "_unload_llama_before_standard_load", _nothing_loaded)++ response = asyncio.run(+ routes._load_npu_model(+ LoadRequest(model_path = model.model_path),+ current_request_counted = False,+ on_reload_confirmed = None,+ load_cancel_event = None,+ )+ )+ assert response.status == "loaded"+ assert routes._loaded_slot_ident() == model.model_path+ assert not account_access.resident_hidden("chat", routes._loaded_slot_ident())++ def _as_bob():+ return account_access.resident_hidden("chat", routes._loaded_slot_ident())++ assert run_as(bob, _as_bob) is True+ with pytest.raises(HTTPException) as info:+ run_as(+ bob,+ asyncio.run,+ routes._unload_model_impl(UnloadRequest(model_path = model.model_path), "bob"),+ )+ assert info.value.status_code == 404+ assert npu.unloads == 0+++def test_npu_status_hides_the_owner_runtime_from_managed_accounts(tmp_path, monkeypatch):+ from routes import npu as npu_routes+ from utils.account_context import AccountContext, arun_as++ backend = nb.LemonadeNpuBackend(root = tmp_path)+ monkeypatch.setattr(+ nb, "detect_amd_npu", lambda: {"present": True, "supported": True, "family": "XDNA2"}+ )+ real = backend.status()+ real["loaded_model"] = "lemonade:qwen3-0.6b-FLM"+ monkeypatch.setattr(backend, "status", lambda: real)+ monkeypatch.setattr(npu_routes, "get_npu_backend", lambda: backend)++ assert asyncio.run(npu_routes.npu_status("owner")) == real+ hidden = asyncio.run(arun_as(AccountContext("b" * 32, "bob"), npu_routes.npu_status("bob")))+ assert hidden["supported"] is False and hidden["loaded_model"] is None+ assert hidden.keys() == real.keys()+++def test_an_unload_naming_another_npu_model_keeps_the_resident(monkeypatch):+ from models.inference import UnloadRequest+ from routes import inference as routes++ class _Npu:+ is_loaded = True+ loaded_model = nb.NpuModel(+ id = "gemma3-4b-FLM",+ checkpoint = "gemma3:4b",+ size_gb = 4.5,+ downloaded = True,+ labels = ("vision", "chat"),+ max_context_length = 131072,+ )+ unloads = 0++ def cancel_load(self, model_id):+ return False++ def unload(self):+ self.unloads += 1++ npu = _Npu()+ monkeypatch.setattr(nb, "peek_npu_backend", lambda: npu)++ def _unload(model_path):+ return asyncio.run(routes._unload_model_impl(UnloadRequest(model_path = model_path), "owner"))++ _unload("lemonade:qwen3-0.6b-FLM")+ assert npu.unloads == 0+ _unload("lemonade:gemma3-4b-FLM")+ assert npu.unloads == 1+++def test_an_npu_load_it_would_refuse_keeps_the_gpu_resident(monkeypatch):+ from models.inference import LoadRequest+ from routes import inference as routes++ class _Npu:+ loaded_model = None+ loaded_context_length = None++ def resident(self):+ return None++ def loadable_model(self, model_id):+ raise nb.NpuError(f"{model_id} is not downloaded yet.")++ def load(self, model_id, ctx):+ raise AssertionError("load() must not run")++ teardowns: list[str] = []++ async def _unload_gpu(_backend):+ teardowns.append("llama")++ monkeypatch.setattr(nb, "get_npu_backend", lambda: _Npu())+ monkeypatch.setattr(routes, "_unload_llama_before_standard_load", _unload_gpu)+ with pytest.raises(HTTPException) as info:+ asyncio.run(+ routes._load_npu_model(+ LoadRequest(model_path = "lemonade:gemma3-4b-FLM"),+ current_request_counted = False,+ on_reload_confirmed = lambda *, cancel: teardowns.append("chats"),+ load_cancel_event = None,+ )+ )+ assert info.value.status_code == 400 and "not downloaded" in info.value.detail+ assert teardowns == []+++def test_a_reply_cut_short_is_not_reported_complete(flm):+ flm()+ status, body = _call(stream = False, messages = [{"role": "user", "content": "CUT"}])+ assert status == 502+ assert "before finishing" in body["error"]["message"]+++def test_a_streamed_reply_cut_short_ends_with_an_error(flm):+ flm()+ status, lines = _call(stream = True, messages = [{"role": "user", "content": "CUT"}])+ assert status == 200+ assert lines[-1] == "data: [DONE]"+ assert "before finishing" in lines[-2]+++ "resident_ctx, requested, expected",+ [+ (16384, 0, "loaded"),+ (None, 16384, "loaded"),+ (16384, 16384, "already_loaded"),+ (None, 0, "already_loaded"),+ ],+)+def test_a_same_model_load_reloads_when_the_context_request_changes(+ monkeypatch, resident_ctx, requested, expected+):+ from models.inference import LoadRequest+ from routes import inference as routes++ model = nb.NpuModel(+ id = "qwen3-0.6b-FLM",+ checkpoint = "qwen3:0.6b",+ size_gb = 0.66,+ downloaded = True,+ labels = ("chat",),+ max_context_length = 40960,+ )++ class _Npu:+ requested = resident_ctx++ def resident(self):+ return nb.NpuResident(+ model = model,+ context_length = self.requested or 8192,+ requested_context_length = self.requested,+ base_url = "http://127.0.0.1:1",+ api_key = "key",+ )++ def loadable_model(self, model_id):+ return model++ def load(self, model_id, ctx):+ self.requested = ctx++ async def _nothing_loaded(_backend):+ return None++ monkeypatch.setattr(nb, "get_npu_backend", lambda: _Npu())+ monkeypatch.setattr(routes, "_peek_inference_backend", lambda: None)+ monkeypatch.setattr(routes, "release_chat_gpu_claim", lambda: True)+ monkeypatch.setattr(routes, "_unload_llama_before_standard_load", _nothing_loaded)+ response = asyncio.run(+ routes._load_npu_model(+ LoadRequest(model_path = model.model_path, max_seq_length = requested),+ current_request_counted = False,+ on_reload_confirmed = None,+ load_cancel_event = None,+ )+ )+ assert response.status == expected++[email protected]("stream", [True, False])+def test_a_stop_sequence_leaves_the_monitor_row_completed(flm, stream):+ from core.inference.api_monitor import api_monitor++ if not api_monitor.enabled:+ pytest.skip("API monitor disabled")+ flm()+ before = api_monitor.active_count()+ _call(stream = stream, stop = ["seven"])+ assert api_monitor.active_count() == before+ assert api_monitor._entries[0].status == "completed"+++def test_a_swap_stops_an_npu_reply_still_in_prefill(flm):+ import routes.inference as ri++ flm()+ payload = ChatCompletionRequest(messages = [{"role": "user", "content": "SLOW"}], stream = True)++ async def go():+ previous = ep_mod._http_client+ client = httpx.AsyncClient()+ ep_mod._http_client = client+ try:+ response = await ri._npu_chat_completions(payload, _request(), "tester")++ async def swap_soon() -> None:+ await asyncio.sleep(1.0)+ ri._raise_or_cancel_active_generations(force = True, action = "Loading a model")++ swap = asyncio.create_task(swap_soon())+ lines = []+ async for piece in response.body_iterator:+ text = piece.decode() if isinstance(piece, bytes) else piece+ lines.extend(line for line in text.split("\n") if line.strip())+ await swap+ return lines+ finally:+ ep_mod._http_client = previous+ await client.aclose()++ lines = asyncio.run(asyncio.wait_for(go(), 15))+ assert lines[-1] == "data: [DONE]"+ assert not any('"error"' in line for line in lines)+ assert _data(lines)[-1]["choices"][0]["finish_reason"] == "stop"+++def test_a_dropped_progress_stream_does_not_stop_the_download(monkeypatch):+ from routes import npu as npu_routes++ finished = threading.Event()+ release = threading.Event()++ class _Npu:+ def download(self, model_id):+ yield {"event": "progress", "percent": 40}+ assert release.wait(10)+ yield {"event": "complete", "model": model_id, "percent": 100}+ finished.set()++ monkeypatch.setattr(npu_routes, "get_npu_backend", lambda: _Npu())++ async def go():+ response = await npu_routes.download_npu_model("qwen3-0.6b-FLM")+ body = response.body_iterator+ first = await body.__anext__()+ await body.aclose()+ return first++ first = asyncio.run(go())+ assert '"percent": 40' in (first.decode() if isinstance(first, bytes) else first)+ release.set()+ assert finished.wait(10)+++def test_a_second_download_request_follows_the_running_pull(monkeypatch):+ from routes import npu as npu_routes++ started: list[str] = []+ release = threading.Event()++ class _Npu:+ def download(self, model_id):+ started.append(model_id)+ assert release.wait(10)+ yield {"event": "complete", "model": model_id, "percent": 100}++ monkeypatch.setattr(npu_routes, "get_npu_backend", lambda: _Npu())+ first = npu_routes._start_download(_Npu(), "gemma3-4b-FLM")+ second = npu_routes._start_download(_Npu(), "gemma3-4b-FLM")+ assert first is second+ release.set()+ assert [event["event"] for event in second.follow()] == ["complete"]+ assert started == ["gemma3-4b-FLM"]++[email protected]("stream", [True, False])+def test_a_reply_cut_short_is_recorded_failed(flm, stream):+ from core.inference.api_monitor import api_monitor++ if not api_monitor.enabled:+ pytest.skip("API monitor disabled")+ flm()+ _call(stream = stream, messages = [{"role": "user", "content": "CUT"}])+ assert api_monitor._entries[0].status == "error"+ assert "before finishing" in api_monitor._entries[0].error+++def test_operator_sampling_pins_reach_fastflowlm(flm, monkeypatch):+ monkeypatch.setenv("UNSLOTH_SAMPLING_TOP_K", "7")+ recorded = flm()+ _call(stream = False)+ assert recorded[-1]["body"]["top_k"] == 7+++def _npu_resident(monkeypatch):+ model = nb.NpuModel(+ id = "qwen3-0.6b-FLM",+ checkpoint = "qwen3:0.6b",+ size_gb = 0.66,+ downloaded = True,+ labels = ("chat",),+ max_context_length = 40960,+ )++ class _Npu:+ loaded_model = model++ monkeypatch.setattr(nb, "peek_npu_backend", lambda: _Npu())+ return model+++def test_the_npu_resident_answers_to_its_own_names_only(monkeypatch):+ from routes import inference as routes++ model = _npu_resident(monkeypatch)+ for name in (model.model_path, model.id):+ assert routes._loaded_satisfies(name)+ assert routes._loaded_identity_satisfies(name)+ for name in ("lemonade:gemma3-4b-FLM", "unsloth/Qwen3-0.6B-GGUF"):+ assert not routes._loaded_satisfies(name)+ assert not routes._loaded_identity_satisfies(name)+++def test_a_request_naming_another_npu_model_is_refused(monkeypatch):+ from routes import inference as routes++ model = _npu_resident(monkeypatch)+ asyncio.run(routes._reject_unservable_model(model.model_path, None))+ with pytest.raises(HTTPException) as caught:+ asyncio.run(routes._reject_unservable_model("lemonade:gemma3-4b-FLM", None))+ assert caught.value.status_code == 404+++def test_a_collected_reply_stops_when_the_caller_leaves(flm):+ import routes.inference as ri+ from starlette.requests import Request++ flm()+ left_at = time.monotonic() + 1.0++ async def receive() -> dict:+ # Starlette polls with a zero timeout, so answer by the clock, not after a sleep.+ if time.monotonic() >= left_at:+ return {"type": "http.disconnect"}+ await asyncio.sleep(3600)+ return {"type": "http.disconnect"}++ request = Request(dict(_request().scope), receive)+ payload = ChatCompletionRequest(messages = [{"role": "user", "content": "SLOW"}], stream = False)++ async def go():+ previous = ep_mod._http_client+ client = httpx.AsyncClient()+ ep_mod._http_client = client+ try:+ return await ri._npu_chat_completions(payload, request, "tester")+ finally:+ ep_mod._http_client = previous+ await client.aclose()++ response = asyncio.run(asyncio.wait_for(go(), 15))+ assert response.status_code == 499+++def test_an_early_scoped_npu_cancel_cancels_the_load_it_names():+ import routes.inference as ri+ from models.inference import LoadRequest, UnloadRequest++ asyncio.run(+ ri._unload_model_impl(+ UnloadRequest(model_path = "lemonade:qwen3-0.6b-FLM", cancel_load_request_id = "npu-r1"),+ "owner",+ )+ )+ attempt = ri._begin_load_attempt(+ LoadRequest(model_path = "lemonade:qwen3-0.6b-FLM", load_request_id = "npu-r1"), "owner"+ )+ try:+ assert attempt.cancel_event.is_set()+ finally:+ ri._finish_load_attempt(attempt)+++def test_a_cancel_racing_the_npu_load_unloads_what_landed(monkeypatch):+ import routes.inference as ri+ from models.inference import LoadRequest++ cancel = threading.Event()+ calls = []+ model = nb.NpuModel("m", "", 0.5, True, ("chat",), 4096)++ class RacingNpu:+ def resident(self):+ return None++ def loadable_model(self, model_id):+ return model++ def load(self, model_id, ctx):+ # The Stop click lands here, before lemond reports the load in flight.+ cancel.set()+ calls.append("load")++ def unload(self):+ calls.append("unload")++ monkeypatch.setattr(nb, "get_npu_backend", lambda: RacingNpu())++ async def noop(*_a, **_k):+ return None++ monkeypatch.setattr(ri, "_unload_llama_before_standard_load", noop)+ monkeypatch.setattr(ri, "_peek_inference_backend", lambda: None)+ monkeypatch.setattr(ri, "release_chat_gpu_claim", lambda: True)+ with pytest.raises(HTTPException) as err:+ asyncio.run(+ ri._load_npu_model(+ LoadRequest(model_path = "lemonade:m"),+ current_request_counted = False,+ on_reload_confirmed = None,+ load_cancel_event = cancel,+ )+ )+ assert err.value.status_code == 409+ assert calls == ["load", "unload"]+++def _finish_after(turns: list[list[str]], owed: str | None = None) -> bool:+ from routes.inference import _TurnFinish++ finish = _TurnFinish()+ for lines in turns:+ for line in lines:+ finish.see(line.strip())+ finish.end_turn()+ if owed is not None:+ finish.see(owed)+ return finish.finished+++def test_a_tool_loop_turn_dropped_after_a_tool_call_is_cut_short():+ called = [_chunk({}, "tool_calls")]+ dropped = [_chunk({"content": "par"})]+ answered = [_chunk({"content": "sunny"}), _chunk({}, "stop")]+ assert _finish_after([called, dropped]) is False+ assert _finish_after([called, answered]) is True+ assert _finish_after([called]) is True+ assert _finish_after([dropped], owed = _chunk({}, "stop").strip()) is True+ from routes.inference import _TurnFinish++ plain = _TurnFinish()+ plain.see(_chunk({}, "stop").strip())+ assert plain.finished is Truediff --git a/studio/backend/tests/test_npu_detect.py b/studio/backend/tests/test_npu_detect.pynew file mode 100644index 00000000000..36a269e20bf--- /dev/null+++ b/studio/backend/tests/test_npu_detect.py@@ -0,0 +1,92 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Linux NPU detection over a fake /sys tree.++The values are the ones the AMD DevLab Strix Halo runner reported (amdxdna 2.25 DKMS,+firmware 1.1.2.65)."""++from __future__ import annotations++import os+from pathlib import Path++import pytest++from utils.hardware import npu+++def _device(+ root: Path,+ name: str,+ vendor: str,+ device: str,+ *,+ driver: str | None = None,+) -> Path:+ # Windows forbids ":" in names; the probe never reads the directory name.+ path = root / "devices" / (name.replace(":", "_") if os.name == "nt" else name)+ path.mkdir(parents = True)+ (path / "vendor").write_text(f"0x{vendor}\n")+ (path / "device").write_text(f"0x{device}\n")+ if driver:+ target = root / "drivers" / driver+ target.mkdir(parents = True, exist_ok = True)+ (path / "driver").symlink_to(target)+ return path+++def test_strix_halo_npu_with_driver(tmp_path):+ _device(tmp_path, "0000:c3:00.0", "1002", "1586", driver = "amdgpu")+ npu_dir = _device(tmp_path, "0000:c4:00.1", "1022", "17f0", driver = "amdxdna")+ (npu_dir / "fw_version").write_text("1.1.2.65\n")+ (npu_dir / "vbnv").write_text("NPU Strix Halo\n")+ (npu_dir / "accel" / "accel0").mkdir(parents = True)+ (tmp_path / "module" / "amdxdna").mkdir(parents = True)+ (tmp_path / "module" / "amdxdna" / "version").write_text("2.25.260102\n")++ assert npu._linux_probe(tmp_path / "devices", tmp_path / "module") == {+ "present": True,+ "family": "XDNA2",+ "name": "NPU Strix Halo",+ "driver": "amdxdna",+ "driver_version": "2.25.260102",+ "firmware_version": "1.1.2.65",+ "device_node": "/dev/accel/accel0",+ }+++def test_an_npu_without_a_driver_is_still_found(tmp_path):+ _device(tmp_path, "0000:c4:00.1", "1022", "17f0")+ info = npu._linux_probe(tmp_path / "devices", tmp_path / "module")+ assert info["present"] is True+ assert info["driver"] is None+ assert info["device_node"] is None+++def test_no_npu(tmp_path):+ _device(tmp_path, "0000:c3:00.0", "1002", "1586", driver = "amdgpu")+ assert npu._linux_probe(tmp_path / "devices") == {"present": False}+ assert npu._linux_probe(tmp_path / "missing") == {"present": False}++[email protected]("device, supported", [("17f0", True), ("1502", False)])+def test_only_xdna2_is_supported(tmp_path, monkeypatch, device, supported):+ _device(tmp_path, "0000:c4:00.1", "1022", device, driver = "amdxdna")+ probe = npu._linux_probe+ monkeypatch.setattr(npu.sys, "platform", "linux")+ monkeypatch.setattr(+ npu, "_linux_probe", lambda: probe(tmp_path / "devices", tmp_path / "module")+ )+ info = npu.detect_amd_npu()+ assert info["present"] is True+ assert info["supported"] is supported+++def test_detection_never_raises(monkeypatch):+ def broken():+ raise PermissionError("sysfs")++ monkeypatch.setattr(npu.sys, "platform", "linux")+ monkeypatch.setattr(npu, "_linux_probe", broken)+ assert npu.detect_amd_npu() == {"present": False, "error": "sysfs", "supported": False}diff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.pyindex 8d896ec1820..8a6eb98cf0b 100644--- a/studio/backend/tests/test_orchestrator_unload_cancel.py+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py@@ -3427,7 +3427,9 @@ def test_every_long_lived_spawner_consults_the_shutdown_latch():backend = Path(__file__).resolve().parent.parentguarded = {"core/export/orchestrator.py",+ "core/inference/lemonade_server.py","core/inference/llama_cpp.py",+ "core/inference/npu_backend.py","core/inference/orchestrator.py","core/inference/sd_cpp_engine.py","core/inference/sd_cpp_server.py",diff --git a/studio/backend/utils/hardware/npu.py b/studio/backend/utils/hardware/npu.pynew file mode 100644index 00000000000..66cf0727bde--- /dev/null+++ b/studio/backend/utils/hardware/npu.py@@ -0,0 +1,130 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Detect AMD NPUs without starting a runtime.++XDNA 2 (1022:17f0) is supported; XDNA 1 (1022:1502) is not.+Runtime readiness is checked separately by ``flm validate``.+"""++from __future__ import annotations++import sys+from pathlib import Path+from typing import Any, Optional++_AMD_VENDOR = "1022"+_XDNA2_DEVICE = "17f0"+_XDNA1_DEVICE = "1502"+_PCI_ROOT = Path("/sys/bus/pci/devices")+_MODULE_ROOT = Path("/sys/module")+++def _read(path: Path) -> Optional[str]:+ try:+ return path.read_text(encoding = "utf-8", errors = "replace").strip()+ except OSError:+ return None+++def _linux_probe(pci_root: Path = _PCI_ROOT, module_root: Path = _MODULE_ROOT) -> dict[str, Any]:+ try:+ devices = sorted(pci_root.iterdir())+ except OSError:+ devices = []+ for device in devices:+ vendor = (_read(device / "vendor") or "").lower().removeprefix("0x")+ product = (_read(device / "device") or "").lower().removeprefix("0x")+ if vendor != _AMD_VENDOR or product not in (_XDNA2_DEVICE, _XDNA1_DEVICE):+ continue+ driver_link = device / "driver"+ driver = driver_link.resolve().name if driver_link.exists() else None+ accel = sorted((device / "accel").glob("accel*")) if (device / "accel").is_dir() else []+ return {+ "present": True,+ "family": "XDNA2" if product == _XDNA2_DEVICE else "XDNA1",+ "name": _read(device / "vbnv") or "AMD NPU",+ "driver": driver,+ "driver_version": _read(module_root / driver / "version") if driver else None,+ "firmware_version": _read(device / "fw_version"),+ "device_node": f"/dev/accel/{accel[0].name}" if accel else None,+ }+ return {"present": False}+++def _windows_probe() -> dict[str, Any]:+ import winreg++ base = r"SYSTEM\CurrentControlSet\Enum\PCI"+ try:+ pci = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, base)+ except OSError:+ return {"present": False}+ with pci:+ index = 0+ while True:+ try:+ hardware_id = winreg.EnumKey(pci, index)+ except OSError:+ return {"present": False}+ index += 1+ upper = hardware_id.upper()+ if not upper.startswith(f"VEN_{_AMD_VENDOR.upper()}&DEV_"):+ continue+ product = upper.split("&DEV_", 1)[1][:4].lower()+ if product not in (_XDNA2_DEVICE, _XDNA1_DEVICE):+ continue+ driver_version = None+ name = None+ try:+ with winreg.OpenKey(pci, hardware_id) as by_id:+ instance = winreg.EnumKey(by_id, 0)+ with winreg.OpenKey(by_id, instance) as device:+ name = _reg_value(device, "FriendlyName") or _reg_value(+ device, "DeviceDesc"+ )+ driver_key = _reg_value(device, "Driver")+ if driver_key:+ with winreg.OpenKey(+ winreg.HKEY_LOCAL_MACHINE,+ rf"SYSTEM\CurrentControlSet\Control\Class\{driver_key}",+ ) as driver:+ driver_version = _reg_value(driver, "DriverVersion")+ except OSError:+ pass+ if name and ";" in name:+ # DeviceDesc is stored as "@oemNN.inf,%key%;Readable name".+ name = name.rsplit(";", 1)[1]+ return {+ "present": True,+ "family": "XDNA2" if product == _XDNA2_DEVICE else "XDNA1",+ "name": name or "AMD NPU",+ "driver": "installed" if driver_version else None,+ "driver_version": driver_version,+ "firmware_version": None,+ "device_node": None,+ }+++def _reg_value(key, name: str) -> Optional[str]:+ import winreg+ try:+ value, _kind = winreg.QueryValueEx(key, name)+ except OSError:+ return None+ return str(value) if value is not None else None+++def detect_amd_npu() -> dict[str, Any]:+ """Return NPU hardware details and whether FastFlowLM supports this platform."""+ try:+ if sys.platform.startswith("linux"):+ info = _linux_probe()+ elif sys.platform == "win32":+ info = _windows_probe()+ else:+ info = {"present": False}+ except Exception as exc: # noqa: BLE001 -- detection must never break startup or /status+ info = {"present": False, "error": str(exc)}+ info["supported"] = bool(info.get("present")) and info.get("family") == "XDNA2"+ return infodiff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 132b6d40db4..73b7513597f 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -79,6 +79,7 @@ import {useNativeModelDrop,useNativePathLeasesSupported,} from "@/features/native-intents";+import { isNpuModelId } from "@/features/npu";import { GuidedTour, useGuidedTourController } from "@/features/tour";import { isTauri } from "@/lib/api-base";import { chatModelLoaded } from "./lib/chat-model-loaded";@@ -2397,6 +2398,7 @@ export function ChatPage({isModelSelectionIntentCurrent,selectModel,+ loadNpuModel,ejectModel,cancelLoading,loadingModel,@@ -3226,6 +3228,13 @@ export function ChatPage({return;}}+ if (isNpuModelId(value)) {+ void loadNpuModel(value, {+ forceReload: meta?.forceReload,+ config: meta?.config,+ });+ return;+ }if (isExternalSelection) {// Any pending local preflight is stale now, even before it has published a loading run.const externalIntentId = invalidatePendingModelSelection();@@ -3470,6 +3479,7 @@ export function ChatPage({[activeThreadId,externalProvidersForChat,+ loadNpuModel,modelsFromStore,stageOrLoad,view,diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex b2015aaf94e..9b0a3f3baab 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -3409,6 +3409,144 @@ export function useChatModelRuntime() {],);+ const loadNpuModel = useCallback(+ async (+ modelPath: string,+ reload?: { forceReload?: boolean; config?: PerModelConfig },+ ) => {+ const store = useChatRuntimeStore.getState();+ if (+ !reload?.forceReload &&+ store.params.checkpoint === modelPath &&+ store.residentCheckpoint === modelPath+ ) {+ return;+ }+ // Context length is the one setting FastFlowLM takes; null (Auto) sends 0 for its default.+ const contextLength = (+ reload?.config ?? resolveInitialConfig(modelPath).config+ ).customContextLength;+ if (loadingModelRef.current ?? store.loadingModelPick) {+ toast.info("Another model is already loading", {+ description: "Wait for it to finish or cancel it first.",+ });+ return;+ }+ const lease = store.beginModelLoading("preparing");+ if (lease === null) {+ toast.info("A model is loading", {+ description: "Wait for it to finish or cancel it first.",+ });+ return;+ }+ loadLifecycleLeaseRef.current = lease;+ const loadIntentId = ++modelSelectionIntentEpoch;+ const displayName = modelDisplayName(+ modelPath.slice(modelPath.indexOf(":") + 1),+ );+ const previous = useChatRuntimeStore.getState();+ const previousCheckpoint = previous.params.checkpoint;+ const previousGgufVariant = previous.activeGgufVariant;+ const abortCtrl = new AbortController();+ const signal = abortCtrl.signal;+ let markLoadRunSettled = () => {};+ const settledPromise = new Promise<void>((resolve) => {+ markLoadRunSettled = resolve;+ });+ // Registered like any local load so Stop loading and a replacing pick can cancel it.+ const loadRun: ActiveModelLoadRun = {+ attemptId: loadIntentId,+ intentId: loadIntentId,+ abortController: abortCtrl,+ requestId: crypto.randomUUID(),+ loadAttemptPath: null,+ cancelPromise: null,+ rollbackCheckpoint: previousCheckpoint,+ rollbackVariant: previousGgufVariant ?? null,+ rollbackLoadId: previous.activeLoadId ?? null,+ rollbackNativePathToken: previous.activeNativePathToken ?? null,+ rollbackNativePathExpiresAtMs:+ previous.activeNativePathExpiresAtMs ?? null,+ rollbackLoadedState: previous,+ residentModelUnloaded: false,+ forceCancelActive: false,+ settledPromise,+ markSettled: markLoadRunSettled,+ };+ activeLoadRunRef.current = loadRun;+ let toastId: string | number | undefined;+ try {+ const stopDecision = await confirmStopRunningChatsIfNeeded(+ "Loading a different model",+ );+ if (!stopDecision.proceed || signal.aborted) return;+ loadAbortRef.current = abortCtrl;+ const loadInfo = {+ id: modelPath,+ displayName,+ isDownloaded: true,+ isCachedLora: false,+ ggufVariant: null,+ nativePathToken: null,+ };+ setModelsError(null);+ setLastModelLoadError(null);+ setLoadingModel(loadInfo);+ loadingModelRef.current = loadInfo;+ useChatRuntimeStore.getState().setLoadingModelPick(pickOf(loadInfo));+ setLoadProgress({ percent: null, label: null, phase: "starting" });+ toastId = toast.loading(`Loading ${displayName} on the NPU`);+ loadToastIdRef.current = toastId;+ loadRun.forceCancelActive = stopDecision.forceCancelActive;+ loadRun.loadAttemptPath = modelPath;+ cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);+ requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);+ await loadModel({+ model_path: modelPath,+ hf_token: null,+ max_seq_length: contextLength ?? 0,+ load_in_4bit: false,+ is_lora: false,+ force_reload: reload?.forceReload === true,+ force_cancel_active: stopDecision.forceCancelActive,+ load_request_id: loadRun.requestId,+ });+ if (signal.aborted) return;+ const status = await getInferenceStatus();+ if (signal.aborted) return;+ useChatRuntimeStore.getState().setCheckpoint(modelPath, null);+ applyActiveModelStatusToStore(status, {+ previousCheckpoint,+ previousGgufVariant,+ seedLoadParams: true,+ });+ syncModelCapabilities(modelPath, status);+ void refreshContextUsage({ afterModelLoad: true });+ toast.success(`${displayName} loaded on the NPU`, {+ id: toastId,+ closeButton: true,+ duration: 4000,+ });+ } catch (error) {+ if (signal.aborted) return;+ const message =+ error instanceof Error ? error.message : "Failed to load model";+ setModelsError(message);+ setLastModelLoadError(message);+ toast.error(message, {+ id: toastId,+ closeButton: true,+ duration: 8000,+ });+ await syncInferenceStatusToStore().catch(() => {});+ } finally {+ resetLoadingUiForRun(loadRun);+ markLoadRunSettled();+ }+ },+ [resetLoadingUiForRun, setLastModelLoadError, setModelsError],+ );+const ejectModel = useCallback(async (): Promise<boolean> => {if (!params.checkpoint) {return false;@@ -3482,6 +3620,7 @@ export function useChatModelRuntime() {return {refresh,selectModel,+ loadNpuModel,ejectModel,cancelLoading,cancelLoadingForReplacement,diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex a24b163badf..3527c0747f0 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -320,8 +320,12 @@ export function applyActiveModelStatusToStore(incoming: status.requested_context_length,// MLX reports a requested context as well, so the rule below is about any// backend that sizes its own window, not llama.cpp alone.- isGguf: (status.is_gguf ?? true) || (status.is_mlx ?? false),- isMlx: status.is_mlx ?? false,+ isGguf:+ (status.is_gguf ?? true) ||+ (status.is_mlx ?? false) ||+ (status.is_npu ?? false),+ // An NPU status echoes the request itself (null for Auto), so like MLX a positive one is a pin.+ isMlx: (status.is_mlx ?? false) || (status.is_npu ?? false),seedLoadParams,modelChanged: slotsModelChanged,// Both fields: a record written before the MLX pin moved still carries it in maxSeqLength.diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 1708dafeca2..7060a684c25 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -212,6 +212,7 @@ export function isMultimodalResponse(export interface LoadModelResponse {is_mlx?: boolean;+ is_npu?: boolean;status: string;model: string;display_name: string;@@ -327,6 +328,7 @@ export interface UnloadModelRequest {export interface InferenceStatusResponse {is_mlx?: boolean;+ is_npu?: boolean;active_model: string | null;model_identifier?: string | null;is_vision: boolean;diff --git a/studio/frontend/src/features/hub/hub.css b/studio/frontend/src/features/hub/hub.cssindex c7623bc3e1e..97aab8d227f 100644--- a/studio/frontend/src/features/hub/hub.css+++ b/studio/frontend/src/features/hub/hub.css@@ -15,6 +15,7 @@--format-checkpoint: #f472b6;--format-adapter: #8b5cf6;--format-mlx: #f59e0b;+ --format-npu: #06b6d4;--status-warning: #eab308;--status-danger: #ef4444;--status-success: #11b686;@@ -30,6 +31,7 @@--format-checkpoint: #f472b6;--format-adapter: #a78bfa;--format-mlx: #fbbf24;+ --format-npu: #22d3ee;--status-warning: #fbbf24;--status-danger: #ef4444;--status-success: #11b686;@@ -41,6 +43,7 @@--color-format-checkpoint: var(--format-checkpoint);--color-format-adapter: var(--format-adapter);--color-format-mlx: var(--format-mlx);+ --color-format-npu: var(--format-npu);--color-status-warning: var(--status-warning);--color-status-danger: var(--status-danger);--color-status-success: var(--status-success);diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsxindex e1cea6794f1..40d2c6afeb8 100644--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx@@ -15,6 +15,7 @@ import type { CapabilityKey } from "@/features/hub";import type { HfTaskFilter } from "@/features/hub/hooks/use-hub-model-search";// eslint-disable-next-line no-restricted-imports -- The settings barrel imports this feature back.import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";+import { useNpuStatus } from "@/features/npu";import { useT } from "@/i18n";import { ChevronDownStandardIcon } from "@/lib/chevron-icons";import { cn } from "@/lib/utils";@@ -391,6 +392,11 @@ function ModelSelectorContent({[loraModels],);+ const [npuStatus, setNpuStatus] = useNpuStatus(open && !task);+ const npu =+ !task && npuStatus?.supported === true+ ? { status: npuStatus, onStatusChange: setNpuStatus }+ : undefined;// Connected sits in the section toggle, shown only with external providers.const hubSectionTabs = useMemo(() =>@@ -644,6 +650,7 @@ function ModelSelectorContent({task={task}catalog={catalog}communityModelPolicy={communityModelPolicy}+ npu={npu}section={effectiveHubSection}sectionToggle={<PillTabsdiff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex aee0851fef2..74044132b08 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -70,6 +70,13 @@ import {pendingDrafterPresentation,} from "@/features/hub";import type { HfTaskFilter } from "@/features/hub/hooks/use-hub-model-search";+import {+ type NpuModel,+ type NpuPickerSource,+ NpuSetupNotice,+ npuRowsFor,+ useNpuCatalog,+} from "@/features/npu";import {useDebouncedValue,useDenseQuantSchemes,@@ -595,12 +602,13 @@ function ParamChip({ label }: { label: string }) {);}-// Format colours: gguf blue, mlx amber, safetensors/checkpoint pink, adapter.+// Format colours: gguf blue, mlx amber, safetensors/checkpoint pink, adapter, npu cyan.const FORMAT_TONE_DOT: Record<FormatTone, string> = {gguf: "bg-format-gguf",mlx: "bg-format-mlx",checkpoint: "bg-format-checkpoint",adapter: "bg-format-adapter",+ npu: "bg-format-npu",};/** Format as a coloured dot ahead of the name, named on hover: a word like "Safetensors" is@@ -2564,13 +2572,15 @@ const FORMAT_FILTER_LABELS: Record<FormatFilter, string> = {gguf: "GGUF",mlx: "MLX",safetensors: "Safetensors",+ npu: "NPU",};-// Dot colors match the row format tags: gguf blue, mlx amber, safetensors pink.+// Dot colors match the row format tags: gguf blue, mlx amber, safetensors pink, npu cyan.const FORMAT_FILTER_DOTS: Partial<Record<FormatFilter, string>> = {gguf: "bg-format-gguf",mlx: "bg-format-mlx",safetensors: "bg-format-checkpoint",+ npu: "bg-format-npu",};const FORMAT_FILTER_OPTIONS: HubOption<FormatFilter>[] = (@@ -2591,6 +2601,9 @@ const FORMAT_FILTER_OPTIONS: HubOption<FormatFilter>[] = (),};});+const FORMAT_FILTER_OPTIONS_WITHOUT_NPU = FORMAT_FILTER_OPTIONS.filter(+ (option) => option.value !== "npu",+);// Connected has no size, download date or load history, so it sorts by what a hosted catalogue// does offer: the connection, or the name.@@ -2753,6 +2766,7 @@ export function HubModelPicker({task,catalog,communityModelPolicy = "none",+ npu,}: {models: ModelOption[];/** Task-runtime downloads using a cache layout the shared Hub inventory cannot represent (for@@ -2785,6 +2799,7 @@ export function HubModelPicker({/** Also surface community models carrying `task`'s pipeline tags, below the unsloth rows.* Opt-in, since the runtime has to load an arbitrary publisher's checkpoint: true of audio. */communityModelPolicy?: CommunityModelPolicy;+ npu?: NpuPickerSource;}) {const gpu = useGpuInfo();const inferenceGpu = useInferenceGpuInfo();@@ -3436,7 +3451,12 @@ export function HubModelPicker({const [downloadedSort, setDownloadedSort] = useState<LocalSortKey>("recent");const [customSort, setCustomSort] = useState<LocalSortKey>("recent");// Format filter toggle for the Unsloth listing.- const [formatFilter, setFormatFilter] = useState<FormatFilter>("all");+ const [chosenFormatFilter, setFormatFilter] = useState<FormatFilter>("all");+ const npuCatalog = useNpuCatalog(npu);+ const formatFilter: FormatFilter =+ chosenFormatFilter === "npu" && !npuCatalog ? "all" : chosenFormatFilter;+ const [npuOnDeviceCollapsed, setNpuOnDeviceCollapsed] = useState(false);+ const [npuBrowseCollapsed, setNpuBrowseCollapsed] = useState(true);// What this picker's task filter has already established about every row it can show; chat// passes none and keeps the full set.const capabilityScope = useMemo<readonly (keyof ModelCapabilities)[] | null>(() => {@@ -4391,6 +4411,23 @@ export function HubModelPicker({formatFilter,loadTimes,]);+ const npuModels = npuCatalog?.models ?? null;+ const npuListed =+ npuCatalog !== null && (formatFilter === "all" || formatFilter === "npu");+ const npuOnDeviceRows = useMemo(+ () =>+ npuListed+ ? npuRowsFor(npuModels, { onDevice: true, query: debouncedQuery })+ : [],+ [npuListed, npuModels, debouncedQuery],+ );+ const npuBrowseRows = useMemo(+ () =>+ npuListed+ ? npuRowsFor(npuModels, { onDevice: false, query: debouncedQuery })+ : [],+ [npuListed, npuModels, debouncedQuery],+ );const unslothAdditionalOnDeviceModels = useMemo(() =>visibleAdditionalOnDeviceModels.filter((model) =>@@ -5417,6 +5454,7 @@ export function HubModelPicker({visibleCachedGguf.length === 0 &&visibleCachedModelRows.length === 0 &&visibleAdditionalOnDeviceModels.length === 0 &&+ npuOnDeviceRows.length === 0 &&sortedLmStudio.length === 0 &&sortedLocalDir.length === 0 &&// Fine-tuned models are on-device too: do not show the empty state above a non-empty Fine-tuned section.@@ -6244,6 +6282,94 @@ export function HubModelPicker({);};+ const renderNpuRow = (model: NpuModel, onDevice: boolean) => {+ if (!npuCatalog) return null;+ const optionKey = makeModelOptionKey(+ onDevice ? "npu-on-device" : "npu",+ model.id,+ );+ const isSelected = value === model.model_path;+ const isLoaded = loadedModelId === model.model_path;+ const downloading = model.id in npuCatalog.downloads;+ const progress = npuCatalog.downloads[model.id];+ const size =+ model.size_gb == null+ ? null+ : model.size_gb < 1+ ? `${Math.round(model.size_gb * 1000)} MB`+ : `${model.size_gb.toFixed(1)} GB`;+ const pick = () =>+ onSelect(model.model_path, {+ source: "local",+ isLora: false,+ isDownloaded: true,+ });+ const row = (+ <ModelRow+ label={model.id}+ meta={+ downloading+ ? `NPU · Downloading${progress == null ? "" : ` ${Math.round(progress)}%`}`+ : `NPU${size ? ` · ${size}` : ""}`+ }+ selected={isSelected}+ loaded={isLoaded}+ downloaded={!onDevice && model.downloaded}+ capabilities={{+ vision: model.supports_vision,+ reasoning: model.supports_reasoning,+ audio: false,+ imageGen: false,+ videoGen: false,+ }}+ alignMeta={onDevice ? "device" : "hub"}+ optionProps={hubModelList.getOptionProps(optionKey, isSelected)}+ onClick={() => {+ if (downloading) return;+ if (model.downloaded) {+ pick();+ return;+ }+ const before = useChatRuntimeStore.getState();+ const chosen = before.params.checkpoint;+ void npuCatalog.download(model).then((done) => {+ const now = useChatRuntimeStore.getState();+ // A model picked while this downloaded is the user's newer choice; keep it.+ if (done && now.params.checkpoint === chosen && !now.loadingModelPick) {+ pick();+ }+ });+ }}+ vramStatus={null}+ className={onDevice ? downloadedRowButtonClassName : undefined}+ />+ );+ if (!onDevice) return <div key={model.id}>{row}</div>;+ return (+ <div key={model.id} className={downloadedRowShellClassName(isSelected)}>+ <div className="min-w-0 flex-1">{row}</div>+ <span className={cn(ROW_ACTIONS_CLASS, "h-6")}>+ <ModelDeleteAction+ ariaLabel={`Delete ${model.id}`}+ title={`Delete ${model.id}?`}+ description="This removes the model's NPU files from this device."+ successMessage={`Deleted ${model.id}`}+ disabled={isLoaded}+ onConfirm={() => npuCatalog.remove(model)}+ />+ </span>+ </div>+ );+ };++ const npuBrowseForcedOpen = formatFilter === "npu" || showHfSection;+ const npuBrowseFolded = !npuBrowseForcedOpen && npuBrowseCollapsed;+ const showNpuBrowse =+ npuCatalog !== null &&+ npuListed &&+ section === "recommended" &&+ (!showHfSection || npuBrowseRows.length > 0);+return (<CapabilityScope.Provider value={capabilityScope}><div className="relative space-y-2">@@ -6334,7 +6460,11 @@ export function HubModelPicker({<div className="flex max-w-full min-w-0 flex-wrap items-center gap-2"><HubOptionMenuvalue={formatFilter}- options={FORMAT_FILTER_OPTIONS}+ options={+ npuCatalog+ ? FORMAT_FILTER_OPTIONS+ : FORMAT_FILTER_OPTIONS_WITHOUT_NPU+ }onValueChange={setFormatFilter}ariaLabel="Filter by format"align="end"@@ -6617,6 +6747,26 @@ export function HubModelPicker({</div>) : null}+ {showDownloaded && npuOnDeviceRows.length > 0 ? (+ <>+ <ListLabel+ divider={+ pinnedRows.length > 0 ||+ unslothCachedGguf.length > 0 ||+ unslothCachedModelRows.length > 0 ||+ unslothAdditionalOnDeviceModels.length > 0 ||+ hasOtherModels+ }+ collapsed={npuOnDeviceCollapsed}+ onToggle={() => setNpuOnDeviceCollapsed((v) => !v)}+ >+ NPU+ </ListLabel>+ {!npuOnDeviceCollapsed &&+ npuOnDeviceRows.map((model) => renderNpuRow(model, true))}+ </>+ ) : null}+{/* Fine-tuned models: always shown on On Device so the train shortcut has a target. Hiddenunder a task filter. */}{section === "downloaded" && !task ? (@@ -7296,8 +7446,37 @@ export function HubModelPicker({</>) : null}- {showRecommendedSection ? (+ {showNpuBrowse && npuCatalog ? (<>+ <ListLabel+ collapsed={npuBrowseFolded}+ onToggle={+ npuBrowseForcedOpen+ ? undefined+ : () => setNpuBrowseCollapsed((v) => !v)+ }+ >+ NPU+ </ListLabel>+ {npuBrowseFolded ? null : (+ <>+ {showHfSection ? null : (+ <NpuSetupNotice catalog={npuCatalog} />+ )}+ {npuBrowseRows.map((model) =>+ renderNpuRow(model, false),+ )}+ </>+ )}+ </>+ ) : null}++ {showRecommendedSection && formatFilter !== "npu" ? (+ <>+ {/* Below the NPU group, the curated list needs its own heading. */}+ {showNpuBrowse ? (+ <ListLabel divider={!npuBrowseFolded}>Unsloth</ListLabel>+ ) : null}{recommendedSearch.isLoading &&recommendedRows.length === 0 ? (<div className="flex items-center gap-2 px-5 py-3">@@ -7538,7 +7717,9 @@ export function HubModelPicker({</>) : null}- {showHfSection && section === "recommended" ? (+ {showHfSection &&+ section === "recommended" &&+ formatFilter !== "npu" ? (<>{searchRowIds.length === 0 && !isLoading ? (filteredRecommendedIds.length === 0 ? (diff --git a/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts b/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.tsindex c3ec2ede290..e771d89c951 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts@@ -45,7 +45,7 @@ export function isRecommendableFormat(}/** Format filter for the listing toggle. "safetensors" means anything that is neither GGUF nor MLX. */-export type FormatFilter = "all" | "gguf" | "mlx" | "safetensors";+export type FormatFilter = "all" | "gguf" | "mlx" | "safetensors" | "npu";export function matchesFormatFilter(id: string,@@ -59,6 +59,8 @@ export function matchesFormatFilter(return isMlxId(id);case "safetensors":return !isGgufId(id, hintedIsGguf) && !isMlxId(id);+ case "npu":+ return false;default:return true;}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/row-meta.ts b/studio/frontend/src/features/model-picker/components/model-selector/row-meta.tsindex bb100a3abb5..2c69ef96233 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/row-meta.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/row-meta.ts@@ -6,12 +6,13 @@import type { LoraModelOption } from "./types";-export type FormatTone = "gguf" | "mlx" | "checkpoint" | "adapter";+export type FormatTone = "gguf" | "mlx" | "checkpoint" | "adapter" | "npu";// Format keyword to DotTag tone. Looked up by full token and by first word, so "Full finetune" resolves via "full".export const FORMAT_TONE: Record<string, FormatTone> = {gguf: "gguf",mlx: "mlx",+ npu: "npu",local: "checkpoint",safetensors: "checkpoint",checkpoint: "checkpoint",diff --git a/studio/frontend/src/features/npu/api.ts b/studio/frontend/src/features/npu/api.tsnew file mode 100644index 00000000000..3c6d860409e--- /dev/null+++ b/studio/frontend/src/features/npu/api.ts@@ -0,0 +1,167 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++/** Model paths the backend loads onto the NPU (`lemonade:<Lemonade model id>`). */+export const NPU_MODEL_PREFIX = "lemonade:";++export function isNpuModelId(+ value: string | null | undefined,+): value is string {+ return typeof value === "string" && value.startsWith(NPU_MODEL_PREFIX);+}++export interface NpuValidation {+ ready: boolean;+ problems: string[];+}++export interface NpuStatus {+ supported: boolean;+ hardware: {+ present: boolean;+ supported: boolean;+ family?: string;+ name?: string;+ driver?: string | null;+ driver_version?: string | null;+ firmware_version?: string | null;+ };+ runtime_installed: boolean;+ runtime_running: boolean;+ state: string;+ ready: boolean;+ error: string | null;+ validation: NpuValidation | null;+ help_url: string | null;+ loaded_model: string | null;+ context_length: number | null;+ loading_model: string | null;+}++export interface NpuModel {+ id: string;+ model_path: string;+ checkpoint: string;+ size_gb: number | null;+ downloaded: boolean;+ labels: string[];+ supports_vision: boolean;+ supports_reasoning: boolean;+ supports_tools: boolean;+ max_context_length: number | null;+}++export function npuRowsFor(+ models: NpuModel[] | null,+ {+ onDevice,+ query,+ }: {+ onDevice: boolean;+ query: string;+ },+): NpuModel[] {+ const needle = query.trim().toLowerCase();+ return (models ?? []).filter(+ (model) =>+ (!onDevice || model.downloaded) &&+ (!needle ||+ `${model.id} ${model.checkpoint}`.toLowerCase().includes(needle)),+ );+}++export interface NpuDownloadEvent {+ event: string;+ percent?: number;+ bytes_downloaded?: number;+ bytes_total?: number;+ file?: string;+ file_index?: number;+ total_files?: number;+ error?: string;+}++export async function getNpuStatus(signal?: AbortSignal): Promise<NpuStatus> {+ const response = await authFetch("/api/npu/status", { signal });+ if (!response.ok) {+ throw new Error(+ await readFastApiError(response, "Could not read the NPU status"),+ );+ }+ return (await response.json()) as NpuStatus;+}++export async function enableNpu(): Promise<NpuStatus> {+ const response = await authFetch("/api/npu/enable", { method: "POST" });+ if (!response.ok) {+ throw new Error(+ await readFastApiError(response, "Could not enable the NPU runtime"),+ );+ }+ return (await response.json()) as NpuStatus;+}++export async function listNpuModels(): Promise<NpuModel[]> {+ const response = await authFetch("/api/npu/models");+ if (!response.ok) {+ throw new Error(+ await readFastApiError(response, "Could not list NPU models"),+ );+ }+ return ((await response.json()) as { models: NpuModel[] }).models;+}++export async function deleteNpuModel(id: string): Promise<void> {+ const response = await authFetch(+ `/api/npu/models/${encodeURIComponent(id)}`,+ {+ method: "DELETE",+ },+ );+ if (!response.ok) {+ throw new Error(+ await readFastApiError(response, "Could not delete the model"),+ );+ }+}++export async function downloadNpuModel(+ id: string,+ onProgress: (event: NpuDownloadEvent) => void,+ signal?: AbortSignal,+): Promise<void> {+ const response = await authFetch(+ `/api/npu/models/${encodeURIComponent(id)}/download`,+ { method: "POST", signal },+ );+ if (!response.ok || !response.body) {+ throw new Error(+ await readFastApiError(response, "Could not download the model"),+ );+ }+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let boundary = buffer.indexOf("\n\n");+ while (boundary >= 0) {+ const frame = buffer.slice(0, boundary);+ buffer = buffer.slice(boundary + 2);+ boundary = buffer.indexOf("\n\n");+ if (!frame.startsWith("data:")) continue;+ const event = JSON.parse(frame.slice(5).trim()) as NpuDownloadEvent;+ if (event.event === "error") {+ throw new Error(event.error || "The download failed");+ }+ onProgress(event);+ if (event.event === "complete") return;+ }+ }+ throw new Error("The download ended before it completed");+}diff --git a/studio/frontend/src/features/npu/index.ts b/studio/frontend/src/features/npu/index.tsnew file mode 100644index 00000000000..71292a456b8--- /dev/null+++ b/studio/frontend/src/features/npu/index.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export {+ isNpuModelId,+ NPU_MODEL_PREFIX,+ type NpuModel,+ type NpuStatus,+ npuRowsFor,+} from "./api";+export { NpuSetupNotice } from "./npu-setup-notice";+export {+ type NpuCatalog,+ type NpuPickerSource,+ useNpuCatalog,+} from "./use-npu-catalog";+export { useNpuStatus } from "./use-npu-status";diff --git a/studio/frontend/src/features/npu/npu-setup-notice.tsx b/studio/frontend/src/features/npu/npu-setup-notice.tsxnew file mode 100644index 00000000000..42cbe23aa9b--- /dev/null+++ b/studio/frontend/src/features/npu/npu-setup-notice.tsx@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import { Spinner } from "@/components/ui/spinner";+import { AlertCircleIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import type { NpuCatalog } from "./use-npu-catalog";++export function NpuSetupNotice({ catalog }: { catalog: NpuCatalog }) {+ const { status, ready, models, listError, enabling, enable } = catalog;+ const problems = status.validation?.problems ?? [];+ return (+ <div className="flex flex-col gap-2 px-2.5 pb-2 text-xs">+ <p className="text-muted-foreground">+ {status.hardware.name ?? "AMD NPU"}: FastFlowLM's own NPU builds, run+ through Lemonade. GGUF models run on the GPU.+ </p>+ {status.error || problems.length > 0 ? (+ <div className="flex gap-2 rounded-lg bg-destructive/10 p-2.5 text-destructive">+ <HugeiconsIcon+ icon={AlertCircleIcon}+ className="mt-0.5 size-3.5 shrink-0"+ />+ <div className="flex flex-col gap-1">+ <span>{status.error ?? problems.join(" ")}</span>+ {status.help_url ? (+ <a+ href={status.help_url}+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-2"+ >+ NPU driver setup+ </a>+ ) : null}+ </div>+ </div>+ ) : null}+ {!ready || !status.runtime_installed ? (+ <div className="flex items-center justify-between gap-3 rounded-lg bg-muted/50 p-3">+ <span className="text-muted-foreground">+ Enabling downloads Lemonade (about 7 MB) and FastFlowLM (about 40+ MB), then checks the NPU driver.+ </span>+ <Button size="sm" onClick={() => void enable()} disabled={enabling}>+ {enabling ? <Spinner className="size-3.5" /> : null}+ {status.state === "failed"+ ? "Try again"+ : status.runtime_installed+ ? "Start NPU runtime"+ : "Enable NPU"}+ </Button>+ </div>+ ) : null}+ {listError ? <p className="text-destructive">{listError}</p> : null}+ {ready && status.runtime_installed && !models && !listError ? (+ <div className="flex justify-center py-2">+ <Spinner className="size-3.5 text-muted-foreground" />+ </div>+ ) : null}+ <p className="text-ui-11 text-muted-foreground">+ Powered by{" "}+ <a+ href="https://github.com/ROCm/FastFlowLM"+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-2"+ >+ FastFlowLM+ </a>{" "}+ and{" "}+ <a+ href="https://github.com/lemonade-sdk/lemonade"+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-2"+ >+ Lemonade+ </a>+ .+ </p>+ </div>+ );+}diff --git a/studio/frontend/src/features/npu/use-npu-catalog.ts b/studio/frontend/src/features/npu/use-npu-catalog.tsnew file mode 100644index 00000000000..fbc24af428b--- /dev/null+++ b/studio/frontend/src/features/npu/use-npu-catalog.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { toast } from "@/lib/toast";+import { useCallback, useEffect, useState } from "react";+import {+ type NpuModel,+ type NpuStatus,+ deleteNpuModel,+ downloadNpuModel,+ enableNpu,+ getNpuStatus,+ listNpuModels,+} from "./api";++export interface NpuPickerSource {+ status: NpuStatus;+ onStatusChange: (status: NpuStatus) => void;+}++export interface NpuCatalog {+ status: NpuStatus;+ ready: boolean;+ models: NpuModel[] | null;+ listError: string | null;+ enabling: boolean;+ downloads: Record<string, number | null>;+ enable: () => Promise<void>;+ download: (model: NpuModel) => Promise<boolean>;+ remove: (model: NpuModel) => Promise<void>;+}++export function useNpuCatalog(+ source: NpuPickerSource | undefined,+): NpuCatalog | null {+ const [models, setModels] = useState<NpuModel[] | null>(null);+ const [listError, setListError] = useState<string | null>(null);+ const [enabling, setEnabling] = useState(false);+ const [downloads, setDownloads] = useState<Record<string, number | null>>({});+ const status = source?.status;+ const onStatusChange = source?.onStatusChange;+ // Listing starts lemond, so wait for a validated runtime.+ const ready = status?.ready === true;++ const refresh = useCallback(async () => {+ try {+ setModels(await listNpuModels());+ setListError(null);+ } catch (error) {+ setListError(error instanceof Error ? error.message : String(error));+ }+ }, []);++ useEffect(() => {+ if (!ready) return;+ let live = true;+ listNpuModels().then(+ (next) => {+ if (!live) return;+ setModels(next);+ setListError(null);+ },+ (error) => {+ if (live) {+ setListError(error instanceof Error ? error.message : String(error));+ }+ },+ );+ return () => {+ live = false;+ };+ }, [ready]);++ const enable = useCallback(async () => {+ if (!onStatusChange) return;+ setEnabling(true);+ try {+ onStatusChange(await enableNpu());+ await refresh();+ } catch (error) {+ toast.error("Could not enable the NPU", {+ description: error instanceof Error ? error.message : String(error),+ });+ await getNpuStatus().then(onStatusChange, () => undefined);+ } finally {+ setEnabling(false);+ }+ }, [onStatusChange, refresh]);++ const download = useCallback(+ async (model: NpuModel) => {+ setDownloads((current) => ({ ...current, [model.id]: null }));+ try {+ await downloadNpuModel(model.id, (event) => {+ if (typeof event.percent === "number") {+ setDownloads((current) => ({+ ...current,+ [model.id]: event.percent ?? null,+ }));+ }+ });+ await refresh();+ return true;+ } catch (error) {+ toast.error(`Could not download ${model.id}`, {+ description: error instanceof Error ? error.message : String(error),+ });+ return false;+ } finally {+ setDownloads((current) => {+ const next = { ...current };+ delete next[model.id];+ return next;+ });+ }+ },+ [refresh],+ );++ const remove = useCallback(+ async (model: NpuModel) => {+ await deleteNpuModel(model.id);+ await refresh();+ },+ [refresh],+ );++ if (!status) return null;+ return {+ status,+ ready: status.ready,+ models,+ listError,+ enabling,+ downloads,+ enable,+ download,+ remove,+ };+}diff --git a/studio/frontend/src/features/npu/use-npu-status.ts b/studio/frontend/src/features/npu/use-npu-status.tsnew file mode 100644index 00000000000..6c67a281a71--- /dev/null+++ b/studio/frontend/src/features/npu/use-npu-status.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useEffect, useState } from "react";+import { type NpuStatus, getNpuStatus } from "./api";++let cached: NpuStatus | null = null;+let pending: Promise<NpuStatus | null> | null = null;++function fetchOnce(): Promise<NpuStatus | null> {+ pending ??= getNpuStatus()+ .then((status) => {+ cached = status;+ return status;+ })+ .catch(() => null)+ .finally(() => {+ pending = null;+ });+ return pending;+}++export function useNpuStatus(+ active = true,+): [NpuStatus | null, (next: NpuStatus) => void] {+ const [status, setStatus] = useState<NpuStatus | null>(cached);+ useEffect(() => {+ if (!active) return;+ let live = true;+ void fetchOnce().then((next) => {+ if (live && next) setStatus(next);+ });+ return () => {+ live = false;+ };+ }, [active]);+ const update = (next: NpuStatus) => {+ cached = next;+ setStatus(next);+ };+ return [status, update];+}diff --git a/studio/frontend/tests/context-pin-survives-load.test.ts b/studio/frontend/tests/context-pin-survives-load.test.tsindex 9d4bb3e9f93..12c102ea855 100644--- a/studio/frontend/tests/context-pin-survives-load.test.ts+++ b/studio/frontend/tests/context-pin-survives-load.test.ts@@ -539,3 +539,24 @@ test("a failed switch rolls back on the backend that served the outgoing model",/const previousIsMlx = residentIsServedByMlx\(\s*\n\s*previousIsGguf,\s*\n\s*platform\.deviceType,\s*\n\s*platform\.chatOnlyReason,\s*\n\s*rollbackState\.loadedIsMlx,\s*\n\s*\);/,);});++test("an NPU load's pin survives hydration: its status echoes the request, null for Auto", () => {+ // Structural: the applier cannot be imported under node's test resolver. It must pass an NPU+ // status through the pin rule the way MLX goes, since both echo what the load asked for.+ assert.match(APPLIER, /isGguf:[\s\S]{0,120}status\.is_npu \?\? false/);+ assert.match(APPLIER, /isMlx: \(status\.is_mlx \?\? false\) \|\| \(status\.is_npu \?\? false\)/);+ const seed = (incoming: number | null) =>+ resolveCtxPinSeed({+ incoming,+ isGguf: true,+ isMlx: true,+ seedLoadParams: true,+ modelChanged: false,+ remembered: null,+ gpuMemoryMode: null,+ gpuLayers: null,+ loadedPin: null,+ });+ assert.equal(seed(16384).customContextLength, 16384);+ assert.equal(seed(null).customContextLength, null);+});diff --git a/studio/frontend/tests/npu-api.test.ts b/studio/frontend/tests/npu-api.test.tsnew file mode 100644index 00000000000..14d5f06df02--- /dev/null+++ b/studio/frontend/tests/npu-api.test.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { matchesFormatFilter } from "../src/features/model-picker/components/model-selector/recommended-fit.ts";+import type * as NpuApi from "../src/features/npu/api.ts";+import * as formatFastApiError from "../src/lib/format-fastapi-error.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++function client(response: () => Response) {+ const requests: { path: string; init?: RequestInit }[] = [];+ const api = loadWithStubs<typeof NpuApi>(+ new URL("../src/features/npu/api.ts", import.meta.url),+ {+ "@/features/auth": {+ authFetch: async (path: string, init?: RequestInit) => {+ requests.push({ path, init });+ return response();+ },+ },+ "@/lib/format-fastapi-error": formatFastApiError,+ },+ );+ return { api, requests };+}++function sse(chunks: string[]): Response {+ const encoder = new TextEncoder();+ return new Response(+ new ReadableStream({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));+ controller.close();+ },+ }),+ { headers: { "Content-Type": "text/event-stream" } },+ );+}++test("recognizes NPU model paths only", () => {+ const { api } = client(() => Response.json({}));+ assert.equal(api.isNpuModelId("lemonade:qwen3-0.6b-FLM"), true);+ assert.equal(api.isNpuModelId("unsloth/Qwen3-0.6B-GGUF"), false);+ assert.equal(api.isNpuModelId(null), false);+});++test("download reports progress across split frames and resolves on complete", async () => {+ const c = client(() =>+ sse([+ 'data: {"event":"progress","percent":10}\n\ndata: {"event":"pro',+ 'gress","percent":55}\n\n',+ 'data: {"event":"complete","percent":100}\n\n',+ ]),+ );+ const seen: number[] = [];+ await c.api.downloadNpuModel("qwen3-0.6b-FLM", (event) => {+ if (typeof event.percent === "number") seen.push(event.percent);+ });+ assert.deepEqual(seen, [10, 55, 100]);+ assert.equal(c.requests[0].path, "/api/npu/models/qwen3-0.6b-FLM/download");+ assert.equal(c.requests[0].init?.method, "POST");+});++test("download rejects on an error event", async () => {+ const c = client(() =>+ sse(['data: {"event":"error","error":"disk full"}\n\n']),+ );+ await assert.rejects(+ c.api.downloadNpuModel("qwen3-0.6b-FLM", () => {}),+ /disk full/,+ );+});++test("download rejects a stream that ends before completing", async () => {+ const c = client(() => sse(['data: {"event":"progress","percent":5}\n\n']));+ await assert.rejects(+ c.api.downloadNpuModel("qwen3-0.6b-FLM", () => {}),+ /ended before it completed/,+ );+});++test("enable surfaces the backend's reason", async () => {+ const c = client(() =>+ Response.json(+ { detail: "The locked-memory limit is too low." },+ { status: 400 },+ ),+ );+ await assert.rejects(c.api.enableNpu(), /locked-memory limit/);+});++test("NPU rows: downloaded ones on device, all of them to browse, by query", () => {+ const { api } = client(() => new Response(null));+ const model = (id: string, downloaded: boolean) => ({+ id,+ model_path: `lemonade:${id}`,+ checkpoint: id.replace("-FLM", ""),+ size_gb: 1,+ downloaded,+ labels: [],+ supports_vision: false,+ supports_reasoning: false,+ supports_tools: false,+ max_context_length: null,+ });+ const models = [model("qwen3-0.6b-FLM", true), model("gemma3-4b-FLM", false)];+ const ids = (onDevice: boolean, query: string) =>+ api.npuRowsFor(models, { onDevice, query }).map((m) => m.id);+ assert.deepEqual(ids(true, ""), ["qwen3-0.6b-FLM"]);+ assert.deepEqual(ids(false, ""), ["qwen3-0.6b-FLM", "gemma3-4b-FLM"]);+ assert.deepEqual(ids(false, " GEMMA "), ["gemma3-4b-FLM"]);+ assert.deepEqual(ids(true, "gemma"), []);+ assert.deepEqual(api.npuRowsFor(null, { onDevice: false, query: "" }), []);+});++test("the picker's NPU format holds no Hub repo", () => {+ for (const [id, gguf] of [+ ["unsloth/Qwen3-0.6B-GGUF", true],+ ["mlx-community/Qwen3-8B-4bit", false],+ ["unsloth/Qwen3-0.6B", false],+ ] as const) {+ assert.equal(matchesFormatFilter(id, gguf, "npu"), false);+ assert.equal(matchesFormatFilter(id, gguf, "all"), true);+ }+});diff --git a/studio/frontend/tests/npu-load-cancel.test.ts b/studio/frontend/tests/npu-load-cancel.test.tsnew file mode 100644index 00000000000..287a589fc4a--- /dev/null+++ b/studio/frontend/tests/npu-load-cancel.test.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Stop loading cancels only the run in activeLoadRunRef, so an NPU load must register one.+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++const runtime = readFileSync(+ fileURLToPath(new URL("../src/features/chat/hooks/use-chat-model-runtime.ts", import.meta.url)),+ "utf8",+);+const start = runtime.indexOf("const loadNpuModel = useCallback(");+const end = runtime.indexOf("const ejectModel = useCallback(", start);+assert.ok(start !== -1 && end > start, "loadNpuModel not found");+const npuLoad = runtime.slice(start, end);++test("Stop loading reaches an NPU load: it owns the shared load slot", () => {+ assert.match(npuLoad, /activeLoadRunRef\.current = loadRun;/);+ assert.match(npuLoad, /loadRun.loadAttemptPath = modelPath;/);+ assert.match(npuLoad, /load_request_id: loadRun\.requestId,/);+});++test("an NPU pick supersedes a local pick still in its preflight", () => {+ assert.match(npuLoad, /const loadIntentId = \+\+modelSelectionIntentEpoch;/);+});++test("a cancel during the status read does not adopt the cancelled model", () => {+ const afterStatus = npuLoad.slice(npuLoad.indexOf("await getInferenceStatus();"));+ assert.ok(+ afterStatus.indexOf("if (signal.aborted) return;") <+ afterStatus.indexOf("setCheckpoint(modelPath, null)"),+ );+});++test("the run releases the slot through its owner and settles last", () => {+ const cleanup = npuLoad.slice(npuLoad.lastIndexOf("} finally {"));+ assert.match(cleanup, /resetLoadingUiForRun\(loadRun\)/);+ assert.doesNotMatch(npuLoad, /\bresetLoadingUi\(\)/);+ assert.ok(cleanup.indexOf("resetLoadingUiForRun") < cleanup.indexOf("markLoadRunSettled();"));+});++test("a finished NPU download does not replace a model picked meanwhile", () => {+ const pickers = readFileSync(+ fileURLToPath(+ new URL("../src/features/model-picker/components/model-selector/pickers.tsx", import.meta.url),+ ),+ "utf8",+ );+ const flow = pickers.slice(pickers.indexOf("void npuCatalog.download(model).then("));+ const guard = flow.indexOf("now.params.checkpoint === chosen");+ assert.ok(guard !== -1 && guard < flow.indexOf("pick();"));+});diff --git a/studio/install_lemonade_prebuilt.py b/studio/install_lemonade_prebuilt.pynew file mode 100644index 00000000000..d7125fc0704--- /dev/null+++ b/studio/install_lemonade_prebuilt.py@@ -0,0 +1,222 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Install pinned Lemonade binaries when the user enables NPU support.++Verify the archive before extraction and pin FastFlowLM's version and checksums in+resources/backend_versions.json for lemond's /v1/install download.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import platform+import shutil+import sys+import tempfile+import threading+import urllib.request+from pathlib import Path+from typing import Callable, Optional++_STUDIO_DIR = os.path.dirname(os.path.abspath(__file__))+if _STUDIO_DIR not in sys.path:+ sys.path.insert(0, _STUDIO_DIR)++import prebuilt_core as core # noqa: E402+from backend.utils.auth_safe import auth_safe_open # noqa: E402++PINS_PATH = Path(_STUDIO_DIR) / "lemonade_prebuilt_pins.json"+MARKER_NAME = "UNSLOTH_LEMONADE_INFO.json"+_CHUNK = 1 << 20+_DOWNLOAD_TIMEOUT_S = 60++ProgressCallback = Callable[[int, Optional[int]], None]+++class LemonadeInstallCancelled(RuntimeError):+ pass+++def load_pins(path: Path = PINS_PATH) -> dict:+ with open(path, encoding = "utf-8") as handle:+ pins = json.load(handle)+ if pins.get("schema_version") != 1:+ raise RuntimeError(f"{path} has an unsupported schema_version.")+ return pins+++def host_asset_key() -> Optional[str]:+ """The pin key for this OS and CPU, or None where Lemonade publishes no FastFlowLM build."""+ machine = platform.machine().lower()+ if machine not in ("x86_64", "amd64", "x64"):+ return None+ if sys.platform.startswith("linux"):+ return "linux-x64"+ if sys.platform == "win32":+ return "windows-x64"+ return None+++def lemond_name() -> str:+ return "lemond.exe" if sys.platform == "win32" else "lemond"+++def install_dir(root: Path, pins: Optional[dict] = None) -> Path:+ pins = pins or load_pins()+ return Path(root) / pins["lemonade"]["version"]+++def installed_lemond(root: Path, pins: Optional[dict] = None) -> Optional[Path]:+ """The lemond binary of a complete install matching the pin, else None."""+ pins = pins or load_pins()+ key = host_asset_key()+ if key is None:+ return None+ target = install_dir(root, pins)+ try:+ marker = json.loads((target / MARKER_NAME).read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ return None+ asset = pins["lemonade"]["assets"][key]+ if marker.get("sha256") != asset["sha256"] or marker.get("asset") != asset["name"]:+ return None+ # A FastFlowLM-only pin change must rewrite backend_versions.json, whose version lemond installs.+ if marker.get("fastflowlm") != pins["fastflowlm"]:+ return None+ binary = target / lemond_name()+ return binary if binary.is_file() else None+++def _download(+ url: str,+ destination: Path,+ *,+ expected_sha256: str,+ progress: Optional[ProgressCallback],+ cancel: Optional[threading.Event],+) -> None:+ digest = hashlib.sha256()+ request = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio"})+ with (+ auth_safe_open(request, timeout = _DOWNLOAD_TIMEOUT_S) as response,+ open(destination, "wb") as handle,+ ):+ total_header = response.headers.get("Content-Length")+ total = int(total_header) if total_header and total_header.isdigit() else None+ done = 0+ while True:+ if cancel is not None and cancel.is_set():+ raise LemonadeInstallCancelled("Lemonade download cancelled.")+ chunk = response.read(_CHUNK)+ if not chunk:+ break+ handle.write(chunk)+ digest.update(chunk)+ done += len(chunk)+ if progress is not None:+ progress(done, total)+ actual = digest.hexdigest()+ if actual != expected_sha256:+ raise core.ReleaseIntegrityError(+ f"{url} has sha256 {actual}, expected {expected_sha256}; refusing to install it."+ )+++def _pin_fastflowlm_checksum(resources: Path, pins: dict) -> None:+ """Pin lemond's FastFlowLM download to the version and digests Unsloth tested."""+ path = resources / "backend_versions.json"+ versions = json.loads(path.read_text(encoding = "utf-8"))+ flm = pins["fastflowlm"]+ versions.setdefault("flm", {})["npu"] = flm["version"]+ github = versions.setdefault("checksums", {}).setdefault("github", {})+ by_tag = github.setdefault(flm["repo"], {}).setdefault(flm["version"], {})+ for asset in flm["assets"].values():+ by_tag[asset["name"]] = f"sha256:{asset['sha256']}"+ core.atomic_write_bytes(path, (json.dumps(versions, indent = 2) + "\n").encode("utf-8"))+++def install(+ root: Path,+ *,+ progress: Optional[ProgressCallback] = None,+ cancel: Optional[threading.Event] = None,+ pins_path: Path = PINS_PATH,+) -> Path:+ """Install pinned lemond under root/<version>, reusing a matching install.++ Verify and extract in a temporary directory before replacing the installation.+ """+ pins = load_pins(pins_path)+ key = host_asset_key()+ if key is None:+ raise RuntimeError(+ "Lemonade publishes FastFlowLM builds for Windows and Linux on x86_64 only."+ )+ root = Path(root)+ target = install_dir(root, pins)+ with core.install_lock(core.install_lock_path(target)):+ existing = installed_lemond(root, pins)+ if existing is not None:+ return existing+ asset = pins["lemonade"]["assets"][key]+ url = core.release_asset_download_url(+ pins["lemonade"]["repo"], f"v{pins['lemonade']['version']}", asset["name"]+ )+ root.mkdir(parents = True, exist_ok = True)+ with tempfile.TemporaryDirectory(prefix = ".lemonade-install-", dir = root) as scratch:+ scratch_dir = Path(scratch)+ archive = scratch_dir / asset["name"]+ _download(+ url, archive, expected_sha256 = asset["sha256"], progress = progress, cancel = cancel+ )+ extracted = scratch_dir / "extracted"+ extracted.mkdir()+ core.extract_archive(archive, extracted)+ core.restore_tar_exec_bits(archive, extracted)+ binaries = sorted(extracted.rglob(lemond_name()))+ if not binaries:+ raise RuntimeError(f"{asset['name']} does not contain {lemond_name()}.")+ payload = binaries[0].parent+ _pin_fastflowlm_checksum(payload / "resources", pins)+ (payload / MARKER_NAME).write_text(+ json.dumps(+ {+ "version": pins["lemonade"]["version"],+ "asset": asset["name"],+ "sha256": asset["sha256"],+ "fastflowlm": pins["fastflowlm"],+ },+ indent = 2,+ )+ + "\n",+ encoding = "utf-8",+ )+ if target.exists():+ shutil.rmtree(target)+ os.replace(payload, target)+ binary = installed_lemond(root, pins)+ if binary is None:+ raise RuntimeError(f"Lemonade install at {target} did not verify.")+ return binary+++def main(argv: Optional[list[str]] = None) -> int:+ parser = argparse.ArgumentParser(description = __doc__.splitlines()[0])+ parser.add_argument(+ "--root",+ type = Path,+ default = Path.home() / ".unsloth" / "studio" / "lemonade",+ help = "Directory that holds one subdirectory per Lemonade version.",+ )+ args = parser.parse_args(argv)+ print(install(args.root))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/studio/lemonade_prebuilt_pins.json b/studio/lemonade_prebuilt_pins.jsonnew file mode 100644index 00000000000..d486af695b5--- /dev/null+++ b/studio/lemonade_prebuilt_pins.json@@ -0,0 +1,33 @@+{+ "schema_version": 1,+ "lemonade": {+ "version": "11.9.0",+ "repo": "lemonade-sdk/lemonade",+ "assets": {+ "linux-x64": {+ "name": "lemonade-embeddable-11.9.0-ubuntu-x64.tar.gz",+ "sha256": "a18beaf78b5e30996087d1387683a6a5b4207cdd50f0a8ed7d7dc88823eb204d",+ "size": 7429447+ },+ "windows-x64": {+ "name": "lemonade-embeddable-11.9.0-windows-x64.zip",+ "sha256": "8311d9089c3f3747eb3ff5cee35c325a20686f7f5911c455763e7edf0619d1c7",+ "size": 5382390+ }+ }+ },+ "fastflowlm": {+ "version": "v1.0.3",+ "repo": "ROCm/FastFlowLM",+ "assets": {+ "linux-x64": {+ "name": "fastflowlm_1.0.3_linux.tar.gz",+ "sha256": "f721254e6a1e06cbd729883e8a4bd583fa396aade761d59bb4333cea8f59ebd1"+ },+ "windows-x64": {+ "name": "fastflowlm_1.0.3_windows_amd64.zip",+ "sha256": "ca92eaf5f01909391100a1e7fde47240489a3a9b93ef5f52ea01b648f46f8a55"+ }+ }+ }+}diff --git a/tests/studio/install/test_install_lemonade_prebuilt.py b/tests/studio/install/test_install_lemonade_prebuilt.pynew file mode 100644index 00000000000..744cac05753--- /dev/null+++ b/tests/studio/install/test_install_lemonade_prebuilt.py@@ -0,0 +1,166 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Test archive integrity, atomic installation, reuse and FastFlowLM pins with a local server."""++from __future__ import annotations++import hashlib+import io+import json+import sys+import tarfile+import threading+import zipfile+from functools import partial+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++import pytest++STUDIO_DIR = Path(__file__).resolve().parents[3] / "studio"+if str(STUDIO_DIR) not in sys.path:+ sys.path.insert(0, str(STUDIO_DIR))++import install_lemonade_prebuilt as lp # noqa: E402+++def _archive(directory: Path, key: str) -> Path:+ top = "lemonade-embeddable-9.9.9"+ binary = "lemond.exe" if key == "windows-x64" else "lemond"+ versions = json.dumps({"flm": {"npu": "v0.0.1"}, "checksums": {"github": {"other/repo": {}}}})+ files = {+ f"{top}/{binary}": b"#!/bin/sh\n",+ f"{top}/resources/backend_versions.json": versions.encode(),+ }+ if key == "windows-x64":+ path = directory / "lemonade.zip"+ with zipfile.ZipFile(path, "w") as archive:+ for name, data in files.items():+ archive.writestr(name, data)+ else:+ path = directory / "lemonade.tar.gz"+ with tarfile.open(path, "w:gz") as archive:+ for name, data in files.items():+ info = tarfile.TarInfo(name)+ info.size = len(data)+ info.mode = 0o755+ archive.addfile(info, io.BytesIO(data))+ return path+++def served(tmp_path, monkeypatch):+ key = lp.host_asset_key()+ if key is None:+ pytest.skip("no Lemonade build for this platform")+ archive = _archive(tmp_path, key)+ sha = hashlib.sha256(archive.read_bytes()).hexdigest()+ httpd = ThreadingHTTPServer(+ ("127.0.0.1", 0), partial(SimpleHTTPRequestHandler, directory = str(tmp_path))+ )+ httpd.requests = 0+ original = httpd.finish_request++ def counted(*args, **kwargs):+ httpd.requests += 1+ return original(*args, **kwargs)++ httpd.finish_request = counted+ thread = threading.Thread(target = httpd.serve_forever, daemon = True)+ thread.start()+ base = f"http://127.0.0.1:{httpd.server_address[1]}"+ monkeypatch.setattr(+ lp.core, "release_asset_download_url", lambda repo, tag, name: f"{base}/{name}"+ )++ def pins(digest: str = sha, flm_version: str = "v1.0.3") -> Path:+ path = tmp_path / "pins.json"+ path.write_text(+ json.dumps(+ {+ "schema_version": 1,+ "lemonade": {+ "version": "9.9.9",+ "repo": "lemonade-sdk/lemonade",+ "assets": {key: {"name": archive.name, "sha256": digest}},+ },+ "fastflowlm": {+ "version": flm_version,+ "repo": "ROCm/FastFlowLM",+ "assets": {key: {"name": "fastflowlm.tar.gz", "sha256": "ab" * 32}},+ },+ }+ )+ )+ return path++ yield pins, httpd+ httpd.shutdown()+ httpd.server_close()+++def test_install_verifies_and_pins_fastflowlm(tmp_path, served):+ pins, _ = served+ path = pins()+ root = tmp_path / "root"+ binary = lp.install(root, pins_path = path)+ assert binary == lp.installed_lemond(root, lp.load_pins(path))+ versions = json.loads((binary.parent / "resources" / "backend_versions.json").read_text())+ assert versions["flm"]["npu"] == "v1.0.3"+ assert versions["checksums"]["github"]["ROCm/FastFlowLM"]["v1.0.3"] == {+ "fastflowlm.tar.gz": "sha256:" + "ab" * 32+ }+ assert "other/repo" in versions["checksums"]["github"]+++def test_a_complete_install_is_not_downloaded_again(tmp_path, served):+ pins, httpd = served+ path = pins()+ root = tmp_path / "root"+ lp.install(root, pins_path = path)+ before = httpd.requests+ lp.install(root, pins_path = path)+ assert httpd.requests == before+++def test_a_fastflowlm_only_pin_bump_repins_lemond(tmp_path, served):+ pins, _ = served+ root = tmp_path / "root"+ lp.install(root, pins_path = pins())+ bumped = pins(flm_version = "v1.0.5")+ # Same Lemonade asset, so only the recorded FastFlowLM pin can tell the install is stale.+ assert lp.installed_lemond(root, lp.load_pins(bumped)) is None+ binary = lp.install(root, pins_path = bumped)+ versions = json.loads((binary.parent / "resources" / "backend_versions.json").read_text())+ assert versions["flm"]["npu"] == "v1.0.5"+++def test_a_digest_mismatch_installs_nothing(tmp_path, served):+ pins, _ = served+ path = pins("00" * 32)+ root = tmp_path / "root"+ with pytest.raises(lp.core.ReleaseIntegrityError):+ lp.install(root, pins_path = path)+ assert lp.installed_lemond(root, lp.load_pins(path)) is None+ assert not (root / "9.9.9").exists()+++def test_a_cancelled_download_installs_nothing(tmp_path, served):+ pins, _ = served+ path = pins()+ root = tmp_path / "root"+ cancel = threading.Event()+ cancel.set()+ with pytest.raises(lp.LemonadeInstallCancelled):+ lp.install(root, pins_path = path, cancel = cancel)+ assert lp.installed_lemond(root, lp.load_pins(path)) is None+++def test_the_shipped_pins_cover_both_npu_platforms():+ pins = lp.load_pins()+ for section in ("lemonade", "fastflowlm"):+ assert set(pins[section]["assets"]) == {"linux-x64", "windows-x64"}+ for asset in pins[section]["assets"].values():+ assert len(asset["sha256"]) == 64+ assert pins["fastflowlm"]["version"].startswith("v")diff --git a/tests/test_installer_interactive_prompts.py b/tests/test_installer_interactive_prompts.pyindex 56b6b322304..a991f3934a5 100644--- a/tests/test_installer_interactive_prompts.py+++ b/tests/test_installer_interactive_prompts.py@@ -44,6 +44,7 @@ SCANNED_SCRIPTS = ENTRY_POINTS + ("scripts/install_rocm_wsl_strixhalo.sh","scripts/uninstall.sh","scripts/uninstall.ps1",+ "studio/install_lemonade_prebuilt.py","studio/install_llama_prebuilt.py","studio/install_manifest.py","studio/install_node_prebuilt.py",