Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Auto-install SSM kernels (causal-conv1d, mamba-ssm) for inference loads (#6535)

Daniel Han2a05426adb89
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index eb31ec1062c..9fe499780e8 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -160,6 +160,112 @@ def _resolve_lora_4bit(mc, load_in_4bit: bool) -> bool:
return load_in_4bit
+def _ensure_ssm_kernels(targets: list, resp_queue: Any) -> bool:
+ """Install the SSM kernels the given model(s) lazy-import in from_pretrained; no-op for
+ non-SSM models, idempotent. Returns True on success; on a fatal mamba-ssm failure sends a
+ 'loaded' failure response and returns False. Call BEFORE importing transformers, which
+ snapshots its optional-backend gates at import (a later install may not be picked up).
+ """
+ try:
+ from utils.ssm_runtime import ensure_ssm_runtime
+ except Exception as exc:
+ logger.debug("ssm_runtime unavailable (%s); skipping SSM kernel pre-install", exc)
+ return True
+
+ _ssm_status = lambda m: _send_response(resp_queue, {"type": "status", "message": m})
+ try:
+ for ssm_target in dict.fromkeys(t for t in targets if t):
+ ensure_ssm_runtime(ssm_target, status_cb = _ssm_status)
+ return True
+ except Exception as exc:
+ _send_response(
+ resp_queue,
+ {
+ "type": "loaded",
+ "success": False,
+ "message": (
+ f"This model needs SSM kernel libraries (causal-conv1d / "
+ f"mamba-ssm) that could not be installed: {exc}"
+ ),
+ "error_kind": "ssm_runtime_install_failed",
+ },
+ )
+ return False
+
+
+def _run_security_gates(
+ targets: list,
+ *,
+ trust_remote_code: bool,
+ hf_token: str | None,
+ approved_fingerprint: str | None,
+ resp_queue: Any,
+ compute_subdirs: bool = True,
+) -> bool:
+ """Malware + (when trust_remote_code) remote-code consent gates over *targets*
+ (model + base). Sends the matching 'loaded' failure and returns False if blocked; True
+ when every target is clear.
+
+ ``compute_subdirs=False`` keeps the gate transformers-free (``security_load_subdirs``
+ imports ``model_config`` -> ``transformers``, which would snapshot optional-backend
+ availability before the SSM kernels are installed): used for the pre-import preflight,
+ where ``_handle_load`` re-runs the authoritative gate with full subdir scoping.
+ """
+ targets = list(dict.fromkeys(t for t in targets if t))
+
+ # A poisoned pickle deserializes during from_pretrained even with trust_remote_code
+ # False, so check HF's security scan every load (for a LoRA, the base deserializes).
+ from utils.security import evaluate_file_security
+
+ if compute_subdirs:
+ from utils.security import security_load_subdirs
+
+ for target in targets:
+ _subdirs = security_load_subdirs(target, hf_token) if compute_subdirs else ()
+ _fs = evaluate_file_security(target, hf_token = hf_token, load_subdirs = _subdirs)
+ if _fs.blocked:
+ _send_response(
+ resp_queue,
+ {
+ "type": "loaded",
+ "success": False,
+ "message": _fs.reason,
+ "error_kind": "malware_blocked",
+ "security": _fs.response_payload(),
+ },
+ )
+ return False
+
+ # Scan auto_map code before it runs; block CRITICAL/HIGH unless pinned-approved. Adapter
+ # and base are scanned as one unit, pinned by a single fingerprint.
+ if trust_remote_code:
+ from utils.security import evaluate_remote_code_consent_for_targets
+ _rc = evaluate_remote_code_consent_for_targets(
+ targets,
+ hf_token = hf_token,
+ trust_remote_code = True,
+ approved_fingerprint = approved_fingerprint,
+ )
+ if _rc.blocked:
+ _send_response(
+ resp_queue,
+ {
+ "type": "loaded",
+ "success": False,
+ "message": (
+ f"Model '{_rc.model_name}' ships custom code flagged as "
+ f"{_rc.max_severity} by the security scan. Review "
+ f"and approve it to proceed."
+ ),
+ "error_kind": "remote_code_blocked",
+ "remote_code": _rc.response_payload(),
+ },
+ )
+ return False
+
+ return True
+
+
def _handle_load(backend, config: dict, resp_queue: Any) -> None:
"""Handle a load command: load a model into the backend."""
try:
@@ -175,61 +281,31 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
"Auto-enabled trust_remote_code for Nemotron model: %s", config["model_name"]
)
- # Malware gate: a poisoned pickle deserializes during from_pretrained even
- # with trust_remote_code False, so check HF's security scan (metadata-only)
- # every load. For a LoRA, gate the base whose weights deserialize.
- from utils.security import evaluate_file_security, security_load_subdirs
-
- malware_targets = [config["model_name"]]
+ # Authoritative gates over the model + the LoRA base resolved via mc. Must run before
+ # the SSM install so a blocked model never triggers a native kernel build.
+ targets = [config["model_name"]]
if mc.is_lora and getattr(mc, "base_model", None):
- malware_targets.append(str(mc.base_model))
- for target in dict.fromkeys(malware_targets):
- _fs = evaluate_file_security(
- target, hf_token = hf_token, load_subdirs = security_load_subdirs(target, hf_token)
- )
- if _fs.blocked:
- _send_response(
- resp_queue,
- {
- "type": "loaded",
- "success": False,
- "message": _fs.reason,
- "error_kind": "malware_blocked",
- "security": _fs.response_payload(),
- },
- )
- return
+ targets.append(str(mc.base_model))
+ if not _run_security_gates(
+ targets,
+ trust_remote_code = trust_remote_code,
+ hf_token = hf_token,
+ approved_fingerprint = config.get("approved_remote_code_fingerprint"),
+ resp_queue = resp_queue,
+ ):
+ return
- # Consent gate: scan auto_map code before it runs; block CRITICAL/HIGH
- # unless pinned-approved. For a LoRA, gate the base whose code runs.
- if trust_remote_code:
- from utils.security import evaluate_remote_code_consent_for_targets
-
- consent_targets = [config["model_name"]]
- if mc.is_lora and getattr(mc, "base_model", None):
- consent_targets.append(str(mc.base_model))
- # Scan adapter + base as one unit, pinned by a single fingerprint.
- _rc = evaluate_remote_code_consent_for_targets(
- consent_targets,
- hf_token = hf_token,
- trust_remote_code = True,
- approved_fingerprint = config.get("approved_remote_code_fingerprint"),
+ # Install SSM/Mamba kernels: a no-op for the initial load (pre-installed before import)
+ # but still needed for a LoRA's base (resolved only now via mc) and in-process loads.
+ # Skip on MLX (no macOS wheel). Probe the base, not the adapter id / local path.
+ if getattr(backend, "device", None) != "mlx":
+ from utils.ssm_runtime import ssm_probe_identifier
+
+ _ssm_base = (
+ str(mc.base_model) if (mc.is_lora and getattr(mc, "base_model", None)) else None
)
- if _rc.blocked:
- _send_response(
- resp_queue,
- {
- "type": "loaded",
- "success": False,
- "message": (
- f"Model '{_rc.model_name}' ships custom code flagged as "
- f"{_rc.max_severity} by the security scan. Review "
- f"and approve it to proceed."
- ),
- "error_kind": "remote_code_blocked",
- "remote_code": _rc.response_payload(),
- },
- )
+ ssm_targets = [ssm_probe_identifier(config["model_name"], _ssm_base)]
+ if not _ensure_ssm_kernels(ssm_targets, resp_queue):
return
# Heartbeat keeps the orchestrator's inactivity deadline alive during slow
@@ -678,9 +754,33 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
)
return
- # ── 1. Activate transformers version BEFORE any ML imports ──
+ # ── Resolve the effective base once, before activation/gates/install (no ML import) ──
+ # A remote LoRA's base is in its Hub adapter_config.json (else surfaced only by ModelConfig
+ # after import). _lora_base is set only for a genuine adapter, never a full fine-tune's base.
+ import json as _json
+
+ _ensure_backend_on_path()
+ from utils.transformers_version import _remote_lora_base, _resolve_base_model
+
+ _hf_token = _clean_token(config.get("hf_token"))
+ _lora_base = None
+ _local_adapter_cfg = Path(model_name) / "adapter_config.json"
+ if _local_adapter_cfg.is_file():
+ try:
+ _lora_base = (
+ _json.loads(_local_adapter_cfg.read_text()).get("base_model_name_or_path") or None
+ )
+ except Exception:
+ _lora_base = None
+ if not _lora_base:
+ _lora_base = _remote_lora_base(model_name, hf_token = _hf_token)
+ # Base for tier activation + the SSM-kernel heuristic: the LoRA base if any, else a full
+ # fine-tune's recorded base from config.json (its name reveals the SSM/sidecar arch).
+ _base = _lora_base or _resolve_base_model(model_name)
+
+ # ── 1. Activate transformers version (on the resolved base) BEFORE any ML imports ──
try:
- _activate_transformers_version(model_name)
+ _activate_transformers_version(_base)
except Exception as exc:
_send_response(
resp_queue,
@@ -704,6 +804,35 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
'Install for better performance: pip install "triton-windows<3.7"'
)
+ # ── 1c. Security gates, then SSM/Mamba kernels, BEFORE importing transformers ──
+ # transformers snapshots its optional-backend gates at import, so a hybrid model's kernels
+ # must be installed before the import below ("mamba-ssm is required" otherwise). The gates
+ # are metadata-only, so run them first and refuse a blocked model before any native build.
+ # Gate only the model + a genuine LoRA base (matching _handle_load), never a full fine-tune's
+ # unloaded base; _handle_load re-runs the authoritative gates with the mc base.
+ _gate_targets = [model_name]
+ if _lora_base:
+ _gate_targets.append(_lora_base)
+ _trust_remote_code = config.get("trust_remote_code", False) or _needs_nemotron_trust(
+ model_name, hf_token = _hf_token
+ )
+ if not _run_security_gates(
+ _gate_targets,
+ trust_remote_code = _trust_remote_code,
+ hf_token = _hf_token,
+ approved_fingerprint = config.get("approved_remote_code_fingerprint"),
+ resp_queue = resp_queue,
+ compute_subdirs = False, # stay transformers-free until the SSM kernels are installed
+ ):
+ return
+ # Probe the resolved base for SSM kernels, not the adapter id / local checkpoint path
+ # (arbitrary names must not match the SSM substrings).
+ from utils.ssm_runtime import ssm_probe_identifier
+
+ _ssm_targets = [ssm_probe_identifier(model_name, _base)]
+ if not _ensure_ssm_kernels(_ssm_targets, resp_queue):
+ return
+
# ── 2. Import ML libraries (fresh in this clean process) ──
try:
_send_response(
diff --git a/studio/backend/tests/test_ssm_runtime.py b/studio/backend/tests/test_ssm_runtime.py
new file mode 100644
index 00000000000..dbf482c8bce
--- /dev/null
+++ b/studio/backend/tests/test_ssm_runtime.py
@@ -0,0 +1,526 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for utils.ssm_runtime: the inference-side auto-install of SSM/Mamba kernels.
+
+Covers detection, wheel-first install, idempotency, the failure path, the inference
+worker wiring, and a drift guard so the constants/detection stay in lockstep with the
+training worker (the original source of this behaviour).
+"""
+
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from utils import ssm_runtime # noqa: E402
+
+
+class _Result:
+ def __init__(
+ self,
+ returncode = 0,
+ stdout = "",
+ ):
+ self.returncode = returncode
+ self.stdout = stdout
+
+
+# ── detection ────────────────────────────────────────────────────────────────
+
+
+ "name",
+ [
+ "unsloth/NVIDIA-Nemotron-3-Nano-4B",
+ "unsloth/Nemotron-3-Nano-30B-A3B",
+ "nvidia/Nemotron-H-8B",
+ "tiiuae/Falcon-H1-0.5B-Instruct",
+ "ibm-granite/granite-4.0-h-micro",
+ "ibm/granitemoehybrid-test",
+ ],
+)
+def test_ssm_models_detected(name):
+ assert ssm_runtime.model_is_ssm(name) is True
+ # every SSM model also needs causal-conv1d
+ assert ssm_runtime.model_wants_causal_conv1d(name) is True
+
+
+ "name",
+ [
+ "Qwen/Qwen3-Next-80B-A3B",
+ "unsloth/Qwen3.5-2B",
+ "LiquidAI/LFM2-1.2B",
+ ],
+)
+def test_causal_conv1d_only_models(name):
+ # linear-attention hybrids need causal-conv1d but not mamba-ssm
+ assert ssm_runtime.model_wants_causal_conv1d(name) is True
+ assert ssm_runtime.model_is_ssm(name) is False
+
+
+ "name",
+ [
+ "unsloth/Llama-3.2-1B-Instruct",
+ "unsloth/Qwen2.5-7B",
+ "unsloth/gemma-3-4b-it",
+ "",
+ None,
+ ],
+)
+def test_non_ssm_models_not_detected(name):
+ assert ssm_runtime.model_is_ssm(name) is False
+ assert ssm_runtime.model_wants_causal_conv1d(name) is False
+
+
+# ── ssm_probe_identifier: match a real model id, never an arbitrary name ───────
+
+
+def test_probe_lora_uses_base_not_adapter_name():
+ # A plain-Llama LoRA whose adapter id contains an SSM substring is not SSM.
+ probe = ssm_runtime.ssm_probe_identifier("user/falcon-h1-lora", "meta-llama/Llama-3-8B")
+ assert probe == "meta-llama/Llama-3-8B"
+ assert ssm_runtime.model_is_ssm(probe) is False
+
+
+def test_probe_lora_on_ssm_base_detected():
+ probe = ssm_runtime.ssm_probe_identifier("user/my-adapter", "nvidia/Nemotron-H-8B")
+ assert ssm_runtime.model_is_ssm(probe) is True
+
+
+def test_probe_plain_hf_id_unchanged():
+ assert ssm_runtime.ssm_probe_identifier("nvidia/Nemotron-H-8B") == "nvidia/Nemotron-H-8B"
+
+
+def test_probe_local_path_uses_basename(tmp_path):
+ # Parent folders are arbitrary: a Llama checkpoint under a falcon-h1 dir is not SSM.
+ d = tmp_path / "falcon-h1-experiment" / "llama-checkpoint"
+ d.mkdir(parents = True)
+ probe = ssm_runtime.ssm_probe_identifier(str(d))
+ assert probe == "llama-checkpoint"
+ assert ssm_runtime.model_is_ssm(probe) is False
+
+
+def test_probe_local_ssm_checkpoint_basename_detected(tmp_path):
+ d = tmp_path / "runs" / "nemotron-h-finetune"
+ d.mkdir(parents = True)
+ assert ssm_runtime.model_is_ssm(ssm_runtime.ssm_probe_identifier(str(d))) is True
+
+
+# ── ensure_ssm_runtime behaviour ─────────────────────────────────────────────
+
+
+def test_noop_for_non_ssm_model(monkeypatch):
+ calls = []
+ monkeypatch.setattr(ssm_runtime, "_install_kernel", lambda **k: calls.append(k) or True)
+ ssm_runtime.ensure_ssm_runtime("unsloth/Llama-3.2-1B-Instruct", run = lambda *a, **k: _Result())
+ assert calls == [] # nothing installed for a plain transformer
+
+
+def test_ssm_model_installs_causal_then_mamba(monkeypatch):
+ order = []
+
+ def fake_install(*, import_name, **_):
+ order.append(import_name)
+ return True
+
+ monkeypatch.setattr(ssm_runtime, "_install_kernel", fake_install)
+ ssm_runtime.ensure_ssm_runtime("unsloth/NVIDIA-Nemotron-3-Nano-4B")
+ assert order == ["causal_conv1d", "mamba_ssm"]
+
+
+def test_causal_only_model_skips_mamba(monkeypatch):
+ order = []
+ monkeypatch.setattr(
+ ssm_runtime,
+ "_install_kernel",
+ lambda *, import_name, **_: order.append(import_name) or True,
+ )
+ ssm_runtime.ensure_ssm_runtime("Qwen/Qwen3-Next-80B-A3B")
+ assert order == ["causal_conv1d"]
+
+
+def test_failure_raises_runtime_error(monkeypatch):
+ # A true SSM model whose mamba-ssm cannot install is fatal (cryptic mid-load import
+ # otherwise). "Nemotron-3-Nano-30B-A3B" matches the SSM substrings.
+ monkeypatch.setattr(ssm_runtime, "_install_kernel", lambda **k: False)
+ with pytest.raises(RuntimeError):
+ ssm_runtime.ensure_ssm_runtime("unsloth/Nemotron-3-Nano-30B-A3B")
+
+
+def test_causal_only_install_failure_is_not_fatal(monkeypatch):
+ # Qwen3-Next/LFM2 want causal-conv1d but fall back to torch; a failed install must
+ # not block the load (best-effort, mirrors training).
+ monkeypatch.setattr(ssm_runtime, "_install_kernel", lambda **k: False)
+ ssm_runtime.ensure_ssm_runtime("Qwen/Qwen3-Next-80B-A3B") # no raise
+
+
+def test_ssm_causal_failure_nonfatal_when_mamba_ok(monkeypatch):
+ # causal-conv1d is best-effort even for a true SSM model; only mamba-ssm is fatal.
+ monkeypatch.setattr(
+ ssm_runtime, "_install_kernel", lambda *, import_name, **_: import_name == "mamba_ssm"
+ )
+ ssm_runtime.ensure_ssm_runtime("unsloth/NVIDIA-Nemotron-3-Nano-4B") # no raise
+
+
+def test_install_kernel_idempotent_when_present(monkeypatch):
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: True)
+ called = []
+ monkeypatch.setattr(ssm_runtime, "url_exists", lambda u: called.append("url") or True)
+ ok = ssm_runtime._install_kernel(
+ import_name = "mamba_ssm",
+ display_name = "mamba-ssm",
+ pypi_name = "mamba-ssm",
+ package_version = "2.3.1",
+ release_tag = "v2.3.1",
+ release_base_url = "x",
+ status_cb = None,
+ run = lambda *a, **k: _Result(),
+ )
+ assert ok is True
+ assert called == [] # short-circuits before touching the network
+
+
+def test_install_kernel_uses_prebuilt_wheel(monkeypatch):
+ # not importable before install, importable after the wheel lands
+ states = iter([False, True])
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: next(states))
+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {"x": "y"})
+ seen = {}
+ monkeypatch.setattr(
+ ssm_runtime,
+ "direct_wheel_url",
+ lambda **k: seen.update(k) or "https://example/mamba_ssm-2.3.1-cp313.whl",
+ )
+ monkeypatch.setattr(ssm_runtime, "url_exists", lambda u: True)
+ installed = {}
+
+ def fake_install_wheel(url, **k):
+ installed["url"] = url
+ return [("uv", _Result(returncode = 0))]
+
+ monkeypatch.setattr(ssm_runtime, "install_wheel", fake_install_wheel)
+ ran = []
+ ok = ssm_runtime._install_kernel(
+ import_name = "mamba_ssm",
+ display_name = "mamba-ssm",
+ pypi_name = "mamba-ssm",
+ package_version = "2.3.1",
+ release_tag = "v2.3.1",
+ release_base_url = "https://github.com/state-spaces/mamba/releases/download",
+ status_cb = None,
+ run = lambda *a, **k: ran.append(a) or _Result(),
+ )
+ assert ok is True
+ assert installed["url"].endswith(".whl")
+ assert seen["filename_prefix"] == "mamba_ssm"
+ assert ran == [] # wheel succeeded; no PyPI source build
+
+
+def test_install_kernel_falls_back_to_source(monkeypatch):
+ # no wheel -> source build -> importable after install
+ states = iter([False, True]) # before install, after install
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: next(states))
+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {})
+ monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
+ pip_cmds = []
+ ok = ssm_runtime._install_kernel(
+ import_name = "causal_conv1d",
+ display_name = "causal-conv1d",
+ pypi_name = "causal-conv1d",
+ package_version = "1.6.1",
+ release_tag = "v1.6.1.post4",
+ release_base_url = "x",
+ status_cb = None,
+ run = lambda cmd, **k: pip_cmds.append(cmd) or _Result(returncode = 0),
+ )
+ assert ok is True
+ assert any("causal-conv1d==1.6.1" in c for c in pip_cmds[0])
+
+
+# ── import-cache invalidation (so a just-installed kernel is importable) ───────
+
+
+def test_is_importable_invalidates_caches(monkeypatch):
+ calls = []
+ monkeypatch.setattr(ssm_runtime.importlib, "invalidate_caches", lambda: calls.append(1))
+ assert ssm_runtime._is_importable("sys") is True
+ assert calls # caches invalidated before attempting the import
+
+
+ "exc",
+ [
+ ImportError("no module"),
+ OSError("undefined symbol: cuLaunchKernel"),
+ RuntimeError("CUDA error: ABI mismatch"),
+ ],
+)
+def test_is_importable_treats_broken_kernel_as_not_importable(monkeypatch, exc):
+ # ABI-incompatible kernels raise OSError/RuntimeError, not ImportError; all must read as
+ # not-importable. _is_importable calls bare __import__(), so patching ssm_runtime.__import__
+ # (resolved via module globals) leaves real `import` statements untouched.
+ def _raise(name):
+ raise exc
+
+ monkeypatch.setattr(ssm_runtime, "__import__", _raise, raising = False)
+ monkeypatch.setattr(ssm_runtime.importlib, "invalidate_caches", lambda: None)
+ assert ssm_runtime._is_importable("causal_conv1d") is False
+
+
+def test_causal_conv1d_skipped_on_windows(monkeypatch):
+ # No prebuilt Windows wheel: a causal-conv1d-only model must NOT enter the source build
+ # (which can hang a chat load for minutes); it falls back to torch.
+ monkeypatch.setattr(ssm_runtime.sys, "platform", "win32")
+ installed = []
+ monkeypatch.setattr(
+ ssm_runtime,
+ "_install_kernel",
+ lambda *, import_name, **_: installed.append(import_name) or True,
+ )
+ ssm_runtime.ensure_ssm_runtime("Qwen/Qwen3-Next-80B-A3B")
+ assert installed == [] # never attempted to build causal-conv1d
+
+
+def test_ssm_model_on_windows_still_installs_mamba(monkeypatch):
+ # A true SSM hybrid still needs mamba-ssm on Windows; only causal-conv1d is skipped.
+ monkeypatch.setattr(ssm_runtime.sys, "platform", "win32")
+ installed = []
+ monkeypatch.setattr(
+ ssm_runtime,
+ "_install_kernel",
+ lambda *, import_name, **_: installed.append(import_name) or True,
+ )
+ ssm_runtime.ensure_ssm_runtime("unsloth/NVIDIA-Nemotron-3-Nano-4B")
+ assert installed == ["mamba_ssm"] # causal-conv1d skipped, mamba-ssm still attempted
+
+
+def test_wheel_installed_but_not_importable_falls_back_to_source(monkeypatch):
+ # top: not importable; after wheel: still not importable (ABI mismatch) -> source build;
+ # after source build: importable.
+ states = iter([False, False, True])
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: next(states))
+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {})
+ monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: "https://x/w.whl")
+ monkeypatch.setattr(ssm_runtime, "url_exists", lambda u: True)
+ monkeypatch.setattr(
+ ssm_runtime, "install_wheel", lambda url, **k: [("uv", _Result(returncode = 0))]
+ )
+ pip_cmds = []
+ ok = ssm_runtime._install_kernel(
+ import_name = "mamba_ssm",
+ display_name = "mamba-ssm",
+ pypi_name = "mamba-ssm",
+ package_version = "2.3.1",
+ release_tag = "v2.3.1",
+ release_base_url = "x",
+ status_cb = None,
+ run = lambda cmd, **k: pip_cmds.append(cmd) or _Result(returncode = 0),
+ )
+ assert ok is True
+ assert pip_cmds, "a non-importable wheel must fall back to a source build"
+
+
+def test_hip_source_build_requires_hipcc(monkeypatch):
+ # ROCm env (hip_version set) with no wheel and no hipcc must fail clearly, not build.
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: False)
+ monkeypatch.setattr(
+ ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {"hip_version": "6.2"}
+ )
+ monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
+ monkeypatch.setattr(ssm_runtime.shutil, "which", lambda name: None) # no uv, no hipcc
+ ran = []
+ ok = ssm_runtime._install_kernel(
+ import_name = "causal_conv1d",
+ display_name = "causal-conv1d",
+ pypi_name = "causal-conv1d",
+ package_version = "1.6.1",
+ release_tag = "v1.6.1.post4",
+ release_base_url = "x",
+ status_cb = None,
+ run = lambda cmd, **k: ran.append(cmd) or _Result(returncode = 0),
+ )
+ assert ok is False
+ assert ran == [] # bailed before invoking pip
+
+
+def test_source_build_reinstalls_to_replace_broken_wheel(monkeypatch):
+ # Reached only when not importable (possibly a broken wheel at the pinned version);
+ # the source build must reinstall so it replaces it instead of no-opping.
+ states = iter([False, True])
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: next(states))
+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {})
+ monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
+ cmds = []
+ ssm_runtime._install_kernel(
+ import_name = "causal_conv1d",
+ display_name = "causal-conv1d",
+ pypi_name = "causal-conv1d",
+ package_version = "1.6.1",
+ release_tag = "v1.6.1.post4",
+ release_base_url = "x",
+ status_cb = None,
+ run = lambda cmd, **k: cmds.append(cmd) or _Result(returncode = 0),
+ )
+ assert "--reinstall" in cmds[0] or "--force-reinstall" in cmds[0]
+
+
+def test_hip_uv_source_build_uses_no_cache(monkeypatch):
+ # ROCm uv source build must skip the cache to avoid reusing stale partial HIP builds.
+ states = iter([False, True])
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: next(states))
+ monkeypatch.setattr(
+ ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {"hip_version": "6.2"}
+ )
+ monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
+ monkeypatch.setattr(ssm_runtime.shutil, "which", lambda name: "/usr/bin/" + name) # uv + hipcc
+ monkeypatch.setattr(ssm_runtime, "_hipcc_gcc_install_dir", lambda: None)
+ cmds = []
+ ssm_runtime._install_kernel(
+ import_name = "causal_conv1d",
+ display_name = "causal-conv1d",
+ pypi_name = "causal-conv1d",
+ package_version = "1.6.1",
+ release_tag = "v1.6.1.post4",
+ release_base_url = "x",
+ status_cb = None,
+ run = lambda cmd, **k: cmds.append(cmd) or _Result(returncode = 0),
+ )
+ assert cmds[0][0] == "uv"
+ assert "--no-cache" in cmds[0] and "--reinstall" in cmds[0]
+
+
+# ── inference worker wiring ───────────────────────────────────────────────────
+
+
+def test_inference_worker_calls_ensure_ssm_runtime():
+ src = (_BACKEND / "core" / "inference" / "worker.py").read_text()
+ assert "from utils.ssm_runtime import ensure_ssm_runtime" in src
+ assert "ensure_ssm_runtime(" in src
+
+
+def test_inference_worker_skips_ssm_on_mlx_and_checks_lora_base():
+ src = (_BACKEND / "core" / "inference" / "worker.py").read_text()
+ # MLX (Apple Silicon) must not try to build CUDA/ROCm SSM kernels.
+ assert 'getattr(backend, "device", None) != "mlx"' in src
+ # A LoRA load must also check its base model, not just the adapter id.
+ assert "mc.base_model" in src
+
+
+def test_inference_worker_resolves_remote_lora_base_pre_import():
+ # A remote LoRA's base (from the Hub adapter_config.json) must be resolved before the
+ # transformers import so its SSM kernels are pre-installed, not too late in _handle_load.
+ src = (_BACKEND / "core" / "inference" / "worker.py").read_text()
+ assert "_remote_lora_base" in src
+
+
+def test_inference_worker_tiers_on_base_and_gates_lora_base_only():
+ src = (_BACKEND / "core" / "inference" / "worker.py").read_text()
+ # Tier activation runs on the resolved base, not the raw adapter id (remote-LoRA fix).
+ assert "_activate_transformers_version(_base)" in src
+ # The gate only adds a genuine LoRA base, never a full fine-tune's recorded (unloaded) base.
+ assert "_gate_targets" in src and "_lora_base" in src
+
+
+def test_inference_worker_probes_base_for_ssm_kernels():
+ # Both the pre-import path and _handle_load must derive SSM targets from a real model id
+ # via ssm_probe_identifier, not the raw adapter id / local checkpoint path.
+ src = (_BACKEND / "core" / "inference" / "worker.py").read_text()
+ assert src.count("ssm_probe_identifier(") >= 2
+
+
+def test_pre_import_gate_is_transformers_free():
+ # The pre-import gate must not import transformers: security_load_subdirs pulls
+ # model_config -> transformers, which would snapshot SSM backend availability before the
+ # kernels install. With load_subdirs=() the malware + consent scans stay transformers-free.
+ import sys as _sys
+ from unittest.mock import patch
+ import utils.security.file_security as fs
+ import utils.security.consent as consent
+
+ for m in list(_sys.modules):
+ if m == "transformers" or m.startswith("transformers.") or m == "utils.models.model_config":
+ _sys.modules.pop(m, None)
+
+ with patch.object(fs, "_fetch_security_status", return_value = None):
+ fs.evaluate_file_security("nvidia/Nemotron-H-8B", load_subdirs = ())
+ with patch.object(
+ consent, "_load_remote_code_configs", return_value = [{"model_type": "nemotron_h"}]
+ ):
+ from utils.security import evaluate_remote_code_consent_for_targets
+ evaluate_remote_code_consent_for_targets(["nvidia/Nemotron-H-8B"], trust_remote_code = True)
+
+ assert "transformers" not in _sys.modules
+ assert "utils.models.model_config" not in _sys.modules
+
+
+def test_pre_import_gate_skips_subdir_computation():
+ # The worker's pre-import preflight must call the gate with compute_subdirs=False so it
+ # never imports model_config/transformers before the SSM kernels are installed.
+ src = (_BACKEND / "core" / "inference" / "worker.py").read_text()
+ assert "compute_subdirs = False" in src
+
+
+def _call_linenos(tree, func_name, call_name):
+ import ast
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name == func_name:
+ return [
+ c.lineno
+ for c in ast.walk(node)
+ if isinstance(c, ast.Call)
+ and isinstance(c.func, ast.Name)
+ and c.func.id == call_name
+ ]
+ return []
+
+
+def test_security_gates_run_before_ssm_install():
+ # The SSM install is name-based and can source-build native packages, so a malware /
+ # blocked-code model must be refused first -- in both the pre-import path and _handle_load.
+ import ast
+ tree = ast.parse((_BACKEND / "core" / "inference" / "worker.py").read_text())
+ for fn in ("run_inference_process", "_handle_load"):
+ gates = _call_linenos(tree, fn, "_run_security_gates")
+ ssm = _call_linenos(tree, fn, "_ensure_ssm_kernels")
+ assert gates, f"{fn} must call _run_security_gates"
+ assert ssm, f"{fn} must call _ensure_ssm_kernels"
+ assert min(gates) < min(ssm), f"{fn} must gate before installing SSM kernels"
+
+
+# ── drift guard vs the training worker (single source of truth) ───────────────
+
+
+def test_constants_match_training_worker():
+ try:
+ from core.training import worker as tw
+ except Exception as exc: # pragma: no cover - only when training deps absent
+ pytest.skip(f"training worker not importable here: {exc}")
+
+ assert set(ssm_runtime.SSM_MODEL_SUBSTRINGS) == set(tw._SSM_MODEL_SUBSTRINGS)
+ assert ssm_runtime.MAMBA_SSM_PACKAGE_VERSION == tw._MAMBA_SSM_PACKAGE_VERSION
+ assert ssm_runtime.MAMBA_SSM_RELEASE_TAG == tw._MAMBA_SSM_RELEASE_TAG
+ assert ssm_runtime.CAUSAL_CONV1D_PACKAGE_VERSION == tw._CAUSAL_CONV1D_PACKAGE_VERSION
+ assert ssm_runtime.CAUSAL_CONV1D_RELEASE_TAG == tw._CAUSAL_CONV1D_RELEASE_TAG
+
+ # detection must agree with the training worker across SSM + non-SSM names
+ for name in (
+ "unsloth/NVIDIA-Nemotron-3-Nano-4B",
+ "nvidia/Nemotron-H-8B",
+ "tiiuae/Falcon-H1-0.5B",
+ "ibm-granite/granite-4.0-h-micro",
+ "Qwen/Qwen3-Next-80B",
+ "LiquidAI/LFM2-1.2B",
+ "unsloth/Llama-3.2-1B-Instruct",
+ "unsloth/Qwen2.5-7B",
+ ):
+ assert ssm_runtime.model_wants_causal_conv1d(name) == tw._model_wants_causal_conv1d(
+ name
+ ), name
diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.py
index 179158079e2..ccce3accc13 100644
--- a/studio/backend/tests/test_transformers_version.py
+++ b/studio/backend/tests/test_transformers_version.py
@@ -31,6 +31,7 @@ sys.modules.setdefault("loggers", _loggers_stub)
from utils.transformers_version import (
_resolve_base_model,
+ _remote_lora_base,
_check_tokenizer_config_needs_v5,
_check_config_needs_510,
_check_config_needs_550,
@@ -136,6 +137,123 @@ class TestResolveBaseModel:
assert result == "meta-llama/Llama-3-8B"
+class TestRemoteLoraBase:
+ """_remote_lora_base reads a remote adapter's base from its Hub adapter_config.json."""
+
+ @staticmethod
+ def _resp(cfg: dict):
+ class _Resp:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def read(self):
+ return json.dumps(cfg).encode()
+
+ return _Resp()
+
+ def test_fetches_base_from_remote_adapter_config(self, monkeypatch):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ cfg = {"base_model_name_or_path": "nvidia/NVIDIA-Nemotron-3-Nano-4B"}
+ with patch("urllib.request.urlopen", return_value = self._resp(cfg)):
+ assert (
+ _remote_lora_base("someuser/my-nemotron-lora") == "nvidia/NVIDIA-Nemotron-3-Nano-4B"
+ )
+
+ def test_local_or_noncanonical_returns_none(self):
+ assert _remote_lora_base("/local/dir/adapter") is None
+ assert _remote_lora_base("plainname") is None
+
+ def test_respects_hf_endpoint(self, monkeypatch):
+ # Enterprise mirror: the fetch must target HF_ENDPOINT, not hardcoded huggingface.co.
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf.mirror.internal")
+ seen = {}
+
+ def fake_urlopen(req, timeout = 10):
+ seen["url"] = req.full_url
+ return self._resp({"base_model_name_or_path": "org/base"})
+
+ with patch("urllib.request.urlopen", side_effect = fake_urlopen):
+ assert _remote_lora_base("user/adapter") == "org/base"
+ assert seen["url"].startswith("https://hf.mirror.internal/user/adapter/raw/main/")
+
+ @staticmethod
+ def _seed_adapter_cache(
+ hub: Path,
+ repo_id: str,
+ base: str,
+ commit: str = "deadbeef",
+ ):
+ repo = hub / ("models--" + repo_id.replace("/", "--"))
+ snap = repo / "snapshots" / commit
+ snap.mkdir(parents = True)
+ (snap / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": base}))
+ (repo / "refs").mkdir(parents = True)
+ (repo / "refs" / "main").write_text(commit)
+
+ def test_offline_reads_base_from_hf_cache(self, tmp_path: Path, monkeypatch):
+ self._seed_adapter_cache(tmp_path, "user/cached-lora", "nvidia/Nemotron-H-8B")
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path))
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ with patch("urllib.request.urlopen") as mock_url:
+ assert _remote_lora_base("user/cached-lora") == "nvidia/Nemotron-H-8B"
+ mock_url.assert_not_called() # offline: cache only, no network
+
+ def test_fetch_failure_falls_back_to_cache(self, tmp_path: Path, monkeypatch):
+ self._seed_adapter_cache(tmp_path, "user/cached-lora", "nvidia/Nemotron-H-8B")
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ with patch("urllib.request.urlopen", side_effect = OSError("boom")):
+ assert _remote_lora_base("user/cached-lora") == "nvidia/Nemotron-H-8B"
+
+ def test_offline_uncached_makes_no_request(self, tmp_path: Path, monkeypatch):
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path))
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ with patch("urllib.request.urlopen") as mock_url:
+ assert _remote_lora_base("org/adapter") is None
+ mock_url.assert_not_called()
+
+ def test_non_adapter_repo_returns_none(self, tmp_path: Path, monkeypatch):
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ with patch("urllib.request.urlopen", side_effect = OSError("boom")):
+ assert _remote_lora_base("org/not-an-adapter") is None
+
+ def test_existing_relative_path_not_treated_as_repo(self, monkeypatch):
+ # An existing one-slash relative path (e.g. outputs/run1) is a local checkpoint, not
+ # a Hub repo: no request, no risk of matching an unrelated remote/cached adapter.
+ import utils.paths as paths
+ monkeypatch.setattr(paths, "is_local_path", lambda p: True)
+ with patch("urllib.request.urlopen") as mock_url:
+ assert _remote_lora_base("outputs/run1") is None
+ mock_url.assert_not_called()
+
+ def test_404_returns_none_not_stale_cache(self, tmp_path: Path, monkeypatch):
+ import urllib.error
+
+ # The repo is now a full model (adapter_config.json 404s) but a stale LoRA snapshot is
+ # cached: a definitive 404 must return None, not the stale base.
+ self._seed_adapter_cache(tmp_path, "user/was-a-lora", "old/base")
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ err = urllib.error.HTTPError("url", 404, "Not Found", {}, None)
+ with patch("urllib.request.urlopen", side_effect = err):
+ assert _remote_lora_base("user/was-a-lora") is None
+
+ def test_transient_http_error_falls_back_to_cache(self, tmp_path: Path, monkeypatch):
+ import urllib.error
+
+ self._seed_adapter_cache(tmp_path, "user/cached-lora", "nvidia/Nemotron-H-8B")
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ err = urllib.error.HTTPError("url", 503, "Service Unavailable", {}, None)
+ with patch("urllib.request.urlopen", side_effect = err):
+ assert _remote_lora_base("user/cached-lora") == "nvidia/Nemotron-H-8B"
+
+
# ---------------------------------------------------------------------------
# _check_tokenizer_config_needs_v5 — local file check
# ---------------------------------------------------------------------------
diff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.py
new file mode 100644
index 00000000000..ca7e2309f9b
--- /dev/null
+++ b/studio/backend/utils/ssm_runtime.py
@@ -0,0 +1,327 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Auto-install the SSM/Mamba kernels a hybrid model needs before it loads.
+
+Mamba/SSM hybrids (Nemotron-H/Nano, Falcon-H1, Granite-4.0-H, GraniteMoEHybrid, ...)
+lazy-``import mamba_ssm`` / ``causal_conv1d`` in their ``modeling_*.py`` during
+``from_pretrained``; absent, the load dies with "mamba-ssm is required ... cannot be
+imported". The training worker installs them wheel-first before a fine-tune; this is the
+shared, callback-based version the inference load path calls so chat behaves the same.
+Detection/versions mirror the training worker (``tests/test_ssm_runtime.py`` guards drift).
+"""
+
+from __future__ import annotations
+
+import importlib
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import threading
+from typing import Any, Callable, Optional
+
+from loggers import get_logger
+from utils.wheel_utils import (
+ direct_wheel_url,
+ install_wheel,
+ probe_torch_wheel_env,
+ url_exists,
+)
+
+logger = get_logger(__name__)
+
+StatusCb = Optional[Callable[[str], None]]
+
+# Pinned wheels, kept in lockstep with core/training/worker.py by tests/test_ssm_runtime.py.
+CAUSAL_CONV1D_PACKAGE_VERSION = "1.6.1"
+CAUSAL_CONV1D_RELEASE_TAG = "v1.6.1.post4"
+CAUSAL_CONV1D_RELEASE_BASE_URL = "https://github.com/Dao-AILab/causal-conv1d/releases/download"
+MAMBA_SSM_PACKAGE_VERSION = "2.3.1"
+MAMBA_SSM_RELEASE_TAG = "v2.3.1"
+MAMBA_SSM_RELEASE_BASE_URL = "https://github.com/state-spaces/mamba/releases/download"
+
+# Lowercased-id substring matches, mirroring the training worker. mamba-ssm models are a
+# subset of the causal-conv1d set.
+SSM_MODEL_SUBSTRINGS = (
+ "nemotron_h",
+ "nemotron-h",
+ "nemotron-3-nano",
+ "falcon_h1",
+ "falcon-h1",
+ "granite-4.0-h",
+ "granitemoehybrid",
+)
+CAUSAL_CONV1D_MODEL_SUBSTRINGS = (
+ "qwen3.5",
+ "qwen3_5",
+ "qwen3.6",
+ "qwen3_6",
+ "qwen3-next",
+ "qwen3_next",
+ "nemotron_h",
+ "nemotron-h",
+ "nemotron-3-nano",
+ "falcon_h1",
+ "falcon-h1",
+ "granite-4.0-h",
+ "granitemoehybrid",
+ "lfm2",
+)
+
+
+def model_is_ssm(model_name: str) -> bool:
+ """Whether *model_name* is a Mamba/SSM hybrid that needs ``mamba_ssm``."""
+ name = (model_name or "").lower()
+ return any(sub in name for sub in SSM_MODEL_SUBSTRINGS)
+
+
+def model_wants_causal_conv1d(model_name: str) -> bool:
+ """Whether *model_name* needs ``causal_conv1d`` (the SSM set plus linear-attention
+ hybrids like Qwen3-Next / LFM2 whose modeling files lazy-import it)."""
+ name = (model_name or "").lower()
+ return any(sub in name for sub in CAUSAL_CONV1D_MODEL_SUBSTRINGS)
+
+
+def ssm_probe_identifier(model_name: str, base: str | None = None) -> str:
+ """The identifier whose architecture decides the SSM kernels.
+
+ The substring match needs a real model id: a LoRA adapter id or a local checkpoint's
+ parent folders are unrelated to its architecture (a Llama LoRA at ``user/falcon-h1-lora``
+ is not SSM). Prefer *base*; for a bare local checkpoint use its basename.
+ """
+ probe = base or model_name
+ if probe == model_name:
+ try:
+ from utils.paths import is_local_path
+ if is_local_path(model_name):
+ probe = os.path.basename((model_name or "").rstrip("/\\")) or model_name
+ except Exception:
+ pass
+ return probe
+
+
+def _is_importable(import_name: str) -> bool:
+ # Invalidate finder caches so a kernel installed earlier in this process is seen.
+ importlib.invalidate_caches()
+ try:
+ __import__(import_name)
+ return True
+ except Exception as exc:
+ # An ABI-incompatible kernel (undefined symbol after a torch/CUDA upgrade) raises
+ # OSError/RuntimeError, not ImportError; treat any failure as "not importable" so the
+ # caller reinstalls/source-builds instead of hard-failing on a merely broken kernel.
+ logger.debug("%s is not importable (%s: %s)", import_name, type(exc).__name__, exc)
+ return False
+
+
+def _emit(status_cb: StatusCb, message: str) -> None:
+ logger.info(message)
+ if status_cb is None:
+ return
+ try:
+ status_cb(message)
+ except Exception: # status is best-effort; never fail a load over a UI message
+ logger.debug("ssm_runtime status callback raised", exc_info = True)
+
+
+def _hipcc_gcc_install_dir() -> Optional[str]:
+ """Highest gcc dir with both runtime and C++ headers, for ROCm clang's
+ ``--gcc-install-dir`` (Ubuntu 24.04 ships gcc-14 runtime without its headers)."""
+ if not sys.platform.startswith("linux") or platform.machine().lower() != "x86_64":
+ return None
+ for ver in (14, 13, 12, 11):
+ if os.path.isdir(f"/usr/lib/gcc/x86_64-linux-gnu/{ver}/include") and os.path.isdir(
+ f"/usr/include/c++/{ver}"
+ ):
+ return f"/usr/lib/gcc/x86_64-linux-gnu/{ver}"
+ return None
+
+
+def _run_with_heartbeat(run, cmd, status_cb, display_name, **kwargs):
+ """Run *cmd* via *run*, emitting a status every 60s so the parent's inactivity
+ timeout isn't tripped by a long (e.g. ROCm) source build."""
+ done = threading.Event()
+
+ def _beat():
+ while not done.wait(60):
+ _emit(status_cb, f"Still building {display_name} (this can take several minutes)...")
+
+ threading.Thread(target = _beat, daemon = True).start()
+ try:
+ return run(cmd, **kwargs)
+ finally:
+ done.set()
+
+
+def _install_kernel(
+ *,
+ import_name: str,
+ display_name: str,
+ pypi_name: str,
+ package_version: str,
+ release_tag: str,
+ release_base_url: str,
+ status_cb: StatusCb,
+ run: Callable[..., Any],
+) -> bool:
+ """Install one kernel wheel-first, then a HIP-aware PyPI source build. Returns True iff
+ importable afterwards; idempotent (no-op when already installed)."""
+ if _is_importable(import_name):
+ logger.info("%s already installed", display_name)
+ return True
+
+ env = probe_torch_wheel_env(timeout = 30)
+ wheel_url = direct_wheel_url(
+ filename_prefix = import_name,
+ package_version = package_version,
+ release_tag = release_tag,
+ release_base_url = release_base_url,
+ env = env,
+ )
+ if wheel_url and url_exists(wheel_url):
+ _emit(status_cb, f"Installing {display_name} (prebuilt kernel) for this model...")
+ for installer, result in install_wheel(
+ wheel_url,
+ python_executable = sys.executable,
+ use_uv = bool(shutil.which("uv")),
+ run = run,
+ ):
+ if getattr(result, "returncode", 1) == 0:
+ # A wheel can install yet fail to import (CUDA/ABI mismatch); verify before
+ # trusting it, else source-build to match the local ABI.
+ if _is_importable(import_name):
+ logger.info("Installed prebuilt %s wheel", display_name)
+ return True
+ logger.warning(
+ "%s wheel installed but not importable; building from source", display_name
+ )
+ break
+ logger.warning(
+ "%s could not install %s wheel:\n%s",
+ installer,
+ display_name,
+ getattr(result, "stdout", ""),
+ )
+ else:
+ logger.info(
+ "No prebuilt %s wheel for this environment (%s); building from source",
+ display_name,
+ wheel_url,
+ )
+
+ # Source build (slow). ROCm has no prebuilt wheel and needs hipcc + a gcc-install-dir shim.
+ spec = f"{pypi_name}=={package_version}"
+ is_hip = bool((env or {}).get("hip_version"))
+ if is_hip and not shutil.which("hipcc"):
+ _emit(status_cb, f"{display_name}: hipcc not found; install the ROCm HIP SDK to build it.")
+ return False
+ _emit(
+ status_cb,
+ f"Building {display_name} from source for this model (this can take several minutes)...",
+ )
+ # Reinstall so the source build replaces a broken wheel instead of no-opping as
+ # "already satisfied"; --no-cache avoids stale partial HIP build artifacts.
+ if shutil.which("uv"):
+ cmd = [
+ "uv",
+ "pip",
+ "install",
+ "--python",
+ sys.executable,
+ "--no-build-isolation",
+ "--no-deps",
+ "--reinstall",
+ ]
+ if is_hip:
+ cmd.append("--no-cache")
+ cmd.append(spec)
+ else:
+ cmd = [
+ sys.executable,
+ "-m",
+ "pip",
+ "install",
+ "--no-build-isolation",
+ "--no-deps",
+ "--no-cache-dir",
+ "--force-reinstall",
+ spec,
+ ]
+
+ run_kwargs: dict[str, Any] = {
+ "stdout": subprocess.PIPE,
+ "stderr": subprocess.STDOUT,
+ "text": True,
+ }
+ if is_hip:
+ run_kwargs["timeout"] = 1800 # ROCm builds can take 10-30 min
+ existing = os.environ.get("HIPCC_COMPILE_FLAGS_APPEND", "")
+ if "--gcc-install-dir" not in existing:
+ gcc_dir = _hipcc_gcc_install_dir()
+ if gcc_dir:
+ _env = os.environ.copy()
+ _env["HIPCC_COMPILE_FLAGS_APPEND"] = (
+ f"{existing} --gcc-install-dir={gcc_dir}".strip()
+ )
+ run_kwargs["env"] = _env
+ try:
+ result = _run_with_heartbeat(run, cmd, status_cb, display_name, **run_kwargs)
+ except subprocess.TimeoutExpired:
+ logger.error("%s source build timed out", display_name)
+ _emit(status_cb, f"{display_name} source build timed out.")
+ return False
+ if getattr(result, "returncode", 1) != 0:
+ logger.warning("%s source install failed:\n%s", display_name, getattr(result, "stdout", ""))
+ return _is_importable(import_name)
+
+
+def ensure_ssm_runtime(
+ model_name: str,
+ *,
+ status_cb: StatusCb = None,
+ run: Callable[..., Any] = subprocess.run,
+) -> None:
+ """Install the SSM kernels *model_name* needs before load, wheel-first; a no-op for
+ non-SSM models and idempotent. Only a true SSM hybrid's ``mamba_ssm`` is fatal (raises
+ ``RuntimeError`` instead of a cryptic mid-load failure); ``causal_conv1d`` is best-effort
+ (Qwen3-Next/LFM2 fall back to torch).
+ """
+ wants_causal_conv1d = model_wants_causal_conv1d(model_name)
+ is_ssm = model_is_ssm(model_name)
+ if not (wants_causal_conv1d or is_ssm):
+ return
+
+ # No prebuilt Windows wheel: skip causal-conv1d on win32 (mirrors training) rather than
+ # dropping a chat load into a multi-minute source build for an optional fast path.
+ if wants_causal_conv1d and sys.platform == "win32":
+ logger.info(
+ "Skipping causal-conv1d on Windows (no prebuilt wheel); using the torch fallback"
+ )
+ wants_causal_conv1d = False
+
+ # causal-conv1d first (SSM modeling files lazy-import it; mamba-ssm's fast path uses it).
+ if wants_causal_conv1d and not _install_kernel(
+ import_name = "causal_conv1d",
+ display_name = "causal-conv1d",
+ pypi_name = "causal-conv1d",
+ package_version = CAUSAL_CONV1D_PACKAGE_VERSION,
+ release_tag = CAUSAL_CONV1D_RELEASE_TAG,
+ release_base_url = CAUSAL_CONV1D_RELEASE_BASE_URL,
+ status_cb = status_cb,
+ run = run,
+ ):
+ logger.warning("causal-conv1d unavailable; continuing on the model's torch fallback")
+
+ if is_ssm and not _install_kernel(
+ import_name = "mamba_ssm",
+ display_name = "mamba-ssm",
+ pypi_name = "mamba-ssm",
+ package_version = MAMBA_SSM_PACKAGE_VERSION,
+ release_tag = MAMBA_SSM_RELEASE_TAG,
+ release_base_url = MAMBA_SSM_RELEASE_BASE_URL,
+ status_cb = status_cb,
+ run = run,
+ ):
+ raise RuntimeError("Could not install mamba-ssm, required by this Mamba model.")
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index fe3d2633418..f1224086bf9 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -282,6 +282,103 @@ def _resolve_base_model(model_name: str) -> str:
return model_name
+def _is_canonical_repo_id(model_name: str) -> bool:
+ """True for a canonical ``owner/repo`` Hub id (not a local or relative path)."""
+ return bool(
+ model_name
+ and model_name.count("/") == 1
+ and model_name[0] not in "/.~"
+ and "\\" not in model_name
+ )
+
+
+def _adapter_base_from_hf_cache(model_name: str) -> str | None:
+ """``base_model_name_or_path`` from a remote adapter's cached ``adapter_config.json``.
+
+ Stdlib path resolution of the HF hub cache (no ``huggingface_hub`` import); the newest
+ snapshot wins. Lets an offline cached LoRA still resolve its base.
+ """
+ if not _is_canonical_repo_id(model_name):
+ return None
+ hub = (
+ os.environ.get("HF_HUB_CACHE")
+ or os.environ.get("HUGGINGFACE_HUB_CACHE")
+ or os.path.join(
+ os.environ.get("HF_HOME") or os.path.expanduser("~/.cache/huggingface"), "hub"
+ )
+ )
+ repo_dir = Path(hub) / ("models--" + model_name.replace("/", "--"))
+ candidates = []
+ ref_main = repo_dir / "refs" / "main"
+
+ def _mtime(p: Path) -> float:
+ try:
+ return p.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ try:
+ if ref_main.is_file():
+ candidates.append(
+ repo_dir / "snapshots" / ref_main.read_text().strip() / "adapter_config.json"
+ )
+ candidates += sorted(
+ repo_dir.glob("snapshots/*/adapter_config.json"), key = _mtime, reverse = True
+ )
+ for cfg_path in candidates:
+ if cfg_path.is_file():
+ base = json.loads(cfg_path.read_text()).get("base_model_name_or_path")
+ return base or None
+ except Exception as exc:
+ logger.debug("HF cache adapter_config.json lookup failed for '%s': %s", model_name, exc)
+ return None
+
+
+def _remote_lora_base(model_name: str, hf_token: str | None = None) -> str | None:
+ """``base_model_name_or_path`` from a remote adapter's ``adapter_config.json``, or None.
+
+ Raw HTTP (no huggingface_hub / transformers import), so a remote LoRA's base is known
+ before any ML import. Offline (or on a transient failure) it reads the local hub cache,
+ since a cached adapter is still loadable; a definitive 404 returns None (the repo is not
+ a LoRA) rather than a stale cached base. Skipped for local/non-canonical ids.
+ """
+ if not _is_canonical_repo_id(model_name):
+ return None
+ try:
+ from utils.paths import is_local_path
+ if is_local_path(model_name):
+ return None # an existing relative path is a local checkpoint, not a Hub repo
+ except Exception:
+ pass
+ if _env_offline():
+ return _adapter_base_from_hf_cache(model_name)
+
+ import urllib.error
+ import urllib.request
+
+ endpoint = (os.environ.get("HF_ENDPOINT") or "https://huggingface.co").rstrip("/")
+ url = f"{endpoint}/{model_name}/raw/main/adapter_config.json"
+ headers = {"User-Agent": "unsloth-studio"}
+ if hf_token:
+ headers["Authorization"] = f"Bearer {hf_token}"
+ try:
+ req = urllib.request.Request(url, headers = headers)
+ with urllib.request.urlopen(req, timeout = 10) as resp:
+ cfg = json.loads(resp.read().decode())
+ base = cfg.get("base_model_name_or_path")
+ if base:
+ logger.info("Resolved remote LoRA adapter '%s' → base model '%s'", model_name, base)
+ return base or None
+ except urllib.error.HTTPError as exc:
+ if exc.code == 404:
+ return None # definitively not a LoRA; do not serve a stale cached base
+ logger.debug("adapter_config.json fetch failed for '%s': %s", model_name, exc)
+ return _adapter_base_from_hf_cache(model_name)
+ except Exception as exc:
+ logger.debug("No remote adapter_config.json for '%s': %s", model_name, exc)
+ return _adapter_base_from_hf_cache(model_name)
+
+
def _check_tokenizer_config_needs_v5(model_name: str) -> bool:
"""True if the model's tokenizer_class requires transformers 5.x.