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: install causal-conv1d and mamba-ssm only when a model needs them (#13861)
Daniel Han90ac3b773434
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 56b5cd67bdb..b6bbcac913d 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -386,22 +386,43 @@ def _resolve_lora_4bit(mc, load_in_4bit: bool) -> bool:return load_in_4bit-def _ensure_ssm_kernels(targets: list, resp_queue: Any) -> bool:+def _ensure_ssm_kernels(+ targets: list,+ resp_queue: Any,+ hf_token: str | None = None,+) -> 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).+ non-SSM models, idempotent. *targets* are ``(probe_identifier, config_target)`` pairs: the+ kernels are decided from the config at ``config_target`` (the resolved base), the name only+ when there is none. 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; an in-process reload clears them after installing."""try:- from utils.ssm_runtime import ensure_ssm_runtime+ from utils.ssm_runtime import (+ ensure_ssm_runtime,+ refresh_transformers_kernel_gates,+ resolved_model_is_ssm,+ resolved_model_wants_causal_conv1d,+ )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)+ for probe, config_target in dict.fromkeys(t for t in targets if t and t[0]):+ config_target = config_target or probe+ ensure_ssm_runtime(+ probe,+ status_cb = _ssm_status,+ # transformers-free: this runs before the worker's transformers import.+ wants_causal_conv1d = resolved_model_wants_causal_conv1d(+ probe, config_target, hf_token, scan_modeling_source = False+ ),+ is_ssm = resolved_model_is_ssm(probe, config_target, hf_token),+ )+ refresh_transformers_kernel_gates()return Trueexcept Exception as exc:_send_response(@@ -690,8 +711,13 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:_ssm_base = (str(mc.base_model) if (mc.is_lora and getattr(mc, "base_model", None)) else None)- ssm_targets = [ssm_probe_identifier(config["model_name"], _ssm_base)]- if not _ensure_ssm_kernels(ssm_targets, resp_queue):+ ssm_targets = [+ (+ ssm_probe_identifier(config["model_name"], _ssm_base),+ _ssm_base or config["model_name"],+ )+ ]+ if not _ensure_ssm_kernels(ssm_targets, resp_queue, hf_token):return# Heartbeat keeps the orchestrator's inactivity deadline alive during slow@@ -2453,8 +2479,8 @@ def run_inference_process(# (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):+ _ssm_targets = [(ssm_probe_identifier(model_name, _base), _base or model_name)]+ if not _ensure_ssm_kernels(_ssm_targets, resp_queue, _hf_token):returntry:diff --git a/studio/backend/core/systemone/clef_runtime.py b/studio/backend/core/systemone/clef_runtime.pyindex 547a6414e10..4a6cb10596f 100644--- a/studio/backend/core/systemone/clef_runtime.py+++ b/studio/backend/core/systemone/clef_runtime.py@@ -46,10 +46,19 @@ class _Events:def _fast_paths(folder: str) -> None:- # The same prebuilt causal-conv1d a Qwen3.5 training run gets; the gated delta kernels ship with- # unsloth_zoo. A failed install leaves transformers' torch path, which is slower but right.+ # Clef is a Qwen3.5 backbone: unsloth_zoo ships its gated delta kernels and a Triton causal conv,+ # so nothing is installed. Where that conv cannot run (switched off, ROCm, no Triton) it gets the+ # prebuilt causal-conv1d a training run would; a failed install leaves transformers' torch path.try:+ from utils.ssm_runtime import zoo_triton_causal_conv1d_usable++ if zoo_triton_causal_conv1d_usable():+ # The hooks below also steer FLA off TileLang where it faults; keep that part.+ from core.training.worker import _guard_fla_tilelang+ _guard_fla_tilelang()+ returnfrom core.training.worker import _ensure_causal_conv1d_fast_path, _install_fast_path_hooks+_ensure_causal_conv1d_fast_path(_Events(), folder, required = True)_install_fast_path_hooks(_Events(), folder, install_causal_conv1d = True)except Exception as exc:diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 8ca0fab5560..a87b0bed37f 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -77,8 +77,8 @@ from utils.kernel_install import (uninstall_command,)from utils.ssm_runtime import (- CAUSAL_CONV1D_MODEL_SUBSTRINGS as _CAUSAL_CONV1D_MODEL_SUBSTRINGS,- SSM_MODEL_SUBSTRINGS as _SSM_MODEL_SUBSTRINGS,+ model_is_ssm as _model_is_ssm,+ model_wants_causal_conv1d as _model_wants_causal_conv1d,)from utils.wheel_utils import (direct_wheel_url,@@ -1326,11 +1326,6 @@ def _decision_has_llm_backbone(model_load_target: str, hf_token: str | None) ->return False-def _model_wants_causal_conv1d(model_name: str) -> bool:- name = model_name.lower()- return any(key in name for key in _CAUSAL_CONV1D_MODEL_SUBSTRINGS)--_hipcc_gcc_install_dir = hipcc_gcc_install_dir@@ -1683,8 +1678,16 @@ def _flash_linear_attention_importable() -> bool:return False-def _ensure_mamba_ssm(event_queue: Any, model_name: str) -> None:- if not any(sub in model_name.lower() for sub in _SSM_MODEL_SUBSTRINGS):+def _ensure_mamba_ssm(+ event_queue: Any,+ model_name: str,+ *,+ required: bool | None = None,+) -> None:+ # `required` is the config-resolved answer (resolved_model_is_ssm); the name is the fallback.+ if required is None:+ required = _model_is_ssm(model_name)+ if not required:returnif sys.platform == "win32" and importlib.util.find_spec("triton") is None:@@ -4025,16 +4028,21 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) -># 2) mamba-ssm + flash-attn keep their substring / size gates.# 3) FLA gated-delta kernels: vendored by unsloth_zoo, nothing to install.# Laya decision models are ModernBERT encoders: none of these apply.- # Clef decision models are Qwen3.5 backbones and need the same gated-delta / conv kernels.+ # Clef decision models are Qwen3.5 backbones: zoo's gated-delta and Triton conv kernels cover them.if (not config.get("is_decision")or config.get("decision_layout") in ("clef", "llm")or _decision_has_llm_backbone(model_load_target, _worker_hf_token(config))):try:- from utils.ssm_runtime import resolved_model_wants_causal_conv1d+ from utils.ssm_runtime import (+ resolved_model_is_ssm,+ resolved_model_wants_causal_conv1d,+ )- wants_causal_conv1d = resolved_model_wants_causal_conv1d(+ is_ssm = resolved_model_is_ssm(model_name, model_load_target, _worker_hf_token(config))+ # Every mamba-ssm model also runs causal-conv1d.+ wants_causal_conv1d = is_ssm or resolved_model_wants_causal_conv1d(model_name,model_load_target,_worker_hf_token(config),@@ -4049,7 +4057,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->model_name,install_causal_conv1d = wants_causal_conv1d,)- _ensure_mamba_ssm(event_queue, model_name)+ _ensure_mamba_ssm(event_queue, model_name, required = is_ssm)_ensure_flash_attn_for_long_context(event_queue,int(config.get("max_seq_length", 2048)),diff --git a/studio/backend/tests/test_clef_fast_paths.py b/studio/backend/tests/test_clef_fast_paths.pynew file mode 100644index 00000000000..3105cb5dcc5--- /dev/null+++ b/studio/backend/tests/test_clef_fast_paths.py@@ -0,0 +1,45 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Clef's fast-path setup: nothing is installed where zoo's Triton conv runs, but the FLA TileLang+guard still applies; elsewhere the prebuilt causal-conv1d is installed as before."""++import sys+from pathlib import Path++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++from core.systemone import clef_runtime # noqa: E402+from core.training import worker # noqa: E402+from utils import ssm_runtime # noqa: E402+++def _record(monkeypatch, usable: bool) -> list[str]:+ calls: list[str] = []+ monkeypatch.setattr(ssm_runtime, "zoo_triton_causal_conv1d_usable", lambda: usable)+ monkeypatch.setattr(worker, "_guard_fla_tilelang", lambda: calls.append("guard"))+ monkeypatch.setattr(+ worker,+ "_ensure_causal_conv1d_fast_path",+ lambda *args, **kwargs: calls.append("install"),+ )+ monkeypatch.setattr(+ worker,+ "_install_fast_path_hooks",+ lambda *args, **kwargs: calls.append("hooks"),+ )+ return calls+++def test_clef_installs_nothing_but_keeps_the_tilelang_guard(monkeypatch):+ calls = _record(monkeypatch, usable = True)+ clef_runtime._fast_paths("/models/clef")+ assert calls == ["guard"]+++def test_clef_installs_causal_conv1d_where_zoo_conv_cannot_run(monkeypatch):+ calls = _record(monkeypatch, usable = False)+ clef_runtime._fast_paths("/models/clef")+ assert calls == ["install", "hooks"]diff --git a/studio/backend/tests/test_kernel_install.py b/studio/backend/tests/test_kernel_install.pyindex 9510ff725c0..c3ab1ab074e 100644--- a/studio/backend/tests/test_kernel_install.py+++ b/studio/backend/tests/test_kernel_install.py@@ -464,24 +464,17 @@ def test_causal_conv1d_still_installs_below_sm80(uv):@pytest.mark.parametrize(- "without_gpu, capability, installs",- [(False, "None", False), (True, "None", True), (True, "7 0", False), (True, "9 0", True)],+ "capability, installs",+ [("None", False), ("7 0", False), ("9 0", True)],)-def test_setup_installs_mamba_ssm_before_a_gpu_is_visible(- uv, monkeypatch, without_gpu, capability, installs-):- # An image build sees no GPU; a visible pre-Ampere one still skips. Linux, so Windows'- # triton-windows gate (its own test) does not answer first.+def test_mamba_ssm_needs_a_visible_sm80_gpu(uv, monkeypatch, capability, installs):+ # No visible GPU or a pre-Ampere one skips. Linux, so Windows' triton-windows gate (its own+ # test) does not answer first.uv(False)monkeypatch.setattr(kernel_install.sys, "platform", "linux")monkeypatch.setattr(kernel_install, "_triton_version", lambda run: (3, 3))run = _Runner([False, True], capability = capability)- assert (- kernel_install.install_kernel(- "mamba_ssm", _COLAB, run = run, exists = lambda url: True, install_without_gpu = without_gpu- )- == 0- )+ assert kernel_install.install_kernel("mamba_ssm", _COLAB, run = run, exists = lambda url: True) == 0assert bool(run.installer_calls) is installsdiff --git a/studio/backend/tests/test_ssm_runtime.py b/studio/backend/tests/test_ssm_runtime.pyindex 7aecaee13df..02f3668666e 100644--- a/studio/backend/tests/test_ssm_runtime.py+++ b/studio/backend/tests/test_ssm_runtime.py@@ -28,6 +28,13 @@ def _clear_offline_environment(monkeypatch):monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)[email protected](autouse = True)+def _cuda_host_with_triton(monkeypatch):+ # A CUDA torch with Triton, where zoo's Triton conv runs; the platform tests below override it.+ monkeypatch.delenv("UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D", raising = False)+ monkeypatch.setattr(ssm_runtime, "_zoo_triton_platform_usable", lambda: True)++class _Result:def __init__(self,@@ -50,6 +57,11 @@ class _Result:"tiiuae/Falcon-H1-0.5B-Instruct","ibm-granite/granite-4.0-h-micro","ibm/granitemoehybrid-test",+ "state-spaces/mamba-2.8b-hf",+ "ai21labs/Jamba-v0.1",+ "Zyphra/Zamba2-7B",+ "ibm/Bamba-9B",+ "tiiuae/falcon-mamba-7b",],)def test_ssm_models_detected(name):@@ -60,16 +72,7 @@ def test_ssm_models_detected(name):@pytest.mark.parametrize("name",- [- "Qwen/Qwen3-Next-80B-A3B",- "unsloth/Qwen3.5-2B",- "LiquidAI/LFM2-1.2B",- "state-spaces/mamba-2.8b-hf",- "ai21labs/Jamba-v0.1",- "Zyphra/Zamba2-7B",- "ibm/Bamba-9B",- "tiiuae/falcon-mamba-7b",- ],+ ["LiquidAI/LFM2-1.2B", "LiquidAI/LFM2-8B-A1B"],)def test_causal_conv1d_only_models(name):# linear-attention hybrids need causal-conv1d but not mamba-ssm@@ -156,7 +159,7 @@ def test_causal_only_model_skips_mamba(monkeypatch):"_install_kernel",lambda *, import_name, **_: order.append(import_name) or True,)- ssm_runtime.ensure_ssm_runtime("Qwen/Qwen3-Next-80B-A3B")+ ssm_runtime.ensure_ssm_runtime("LiquidAI/LFM2-1.2B")assert order == ["causal_conv1d"]@@ -169,10 +172,10 @@ def test_failure_raises_runtime_error(monkeypatch):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+ # LFM2 wants causal-conv1d but falls 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+ ssm_runtime.ensure_ssm_runtime("LiquidAI/LFM2-1.2B") # no raisedef test_ssm_causal_failure_nonfatal_when_mamba_ok(monkeypatch):@@ -464,7 +467,7 @@ def test_causal_conv1d_attempted_on_windows(monkeypatch):"_install_kernel",lambda *, import_name, **_: installed.append(import_name) or True,)- ssm_runtime.ensure_ssm_runtime("Qwen/Qwen3-Next-80B-A3B")+ ssm_runtime.ensure_ssm_runtime("LiquidAI/LFM2-1.2B")assert installed == ["causal_conv1d"]@@ -679,7 +682,7 @@ def test_hip_uv_source_build_uses_no_cache(monkeypatch):def test_inference_worker_calls_ensure_ssm_runtime():src = (_BACKEND / "core" / "inference" / "worker.py").read_text(encoding = "utf-8")- assert "from utils.ssm_runtime import ensure_ssm_runtime" in src+ assert "from utils.ssm_runtime import (\n ensure_ssm_runtime," in srcassert "ensure_ssm_runtime(" in src@@ -802,8 +805,8 @@ def test_constants_shared_with_training_worker():pytest.skip(f"training worker not importable here: {exc}")from utils import kernel_install- assert tw._SSM_MODEL_SUBSTRINGS is ssm_runtime.SSM_MODEL_SUBSTRINGS- assert tw._CAUSAL_CONV1D_MODEL_SUBSTRINGS is ssm_runtime.CAUSAL_CONV1D_MODEL_SUBSTRINGS+ assert tw._model_is_ssm is ssm_runtime.model_is_ssm+ assert tw._model_wants_causal_conv1d is ssm_runtime.model_wants_causal_conv1dassert tw.CAUSAL_CONV1D is ssm_runtime.CAUSAL_CONV1D is kernel_install.CAUSAL_CONV1Dassert tw.MAMBA_SSM is ssm_runtime.MAMBA_SSM is kernel_install.MAMBA_SSMassert tw._hipcc_gcc_install_dir is ssm_runtime._hipcc_gcc_install_dir@@ -815,6 +818,7 @@ def test_constants_shared_with_training_worker():"tiiuae/Falcon-H1-0.5B","ibm-granite/granite-4.0-h-micro","Qwen/Qwen3-Next-80B",+ "unsloth/Qwen3.5-2B","LiquidAI/LFM2-1.2B","state-spaces/mamba-2.8b-hf","ai21labs/Jamba-v0.1",@@ -838,11 +842,11 @@ def _write_config(directory: Path, config: dict) -> Path:def test_renamed_local_checkpoint_resolves_causal_conv1d_from_its_config(tmp_path):- """A local Qwen3-Next checkpoint whose folder has no allowlisted substring must+ """A local LFM2 checkpoint whose folder has no allowlisted substring muststill be detected, so the availability hook is installed for it."""checkpoint = _write_config(tmp_path / "my-model",- {"model_type": "qwen3_next", "architectures": ["Qwen3NextForCausalLM"]},+ {"model_type": "lfm2", "architectures": ["Lfm2ForCausalLM"]},)target = str(checkpoint)@@ -877,3 +881,325 @@ def test_nested_text_config_resolves_causal_conv1d(tmp_path):target = str(checkpoint)assert ssm_runtime.model_wants_causal_conv1d(target) is Falseassert ssm_runtime.resolved_model_wants_causal_conv1d(target, target, None) is True+++# ── Qwen3.5 / 3.6 / Qwen3-Next run on unsloth-zoo's Triton conv, never causal-conv1d ──+++_ZOO_GDN_NAMES = [+ "Qwen/Qwen3-Next-80B-A3B",+ "Qwen/Qwen3-Next-80B-A3B-Instruct",+ "unsloth/Qwen3.5-2B",+ "unsloth/Qwen3.5-35B-A3B-GGUF",+ "unsloth/Qwen3.6-27B",+ "my-org/qwen3_5-finetune",+]++[email protected]("name", _ZOO_GDN_NAMES)+def test_zoo_gdn_models_request_no_kernels(monkeypatch, name):+ monkeypatch.delenv(ssm_runtime.ZOO_TRITON_CAUSAL_CONV1D_KILL_SWITCH, raising = False)+ assert ssm_runtime.model_wants_causal_conv1d(name) is False+ assert ssm_runtime.model_is_ssm(name) is False+ installed = []+ monkeypatch.setattr(+ ssm_runtime,+ "_install_kernel",+ lambda *, import_name, **_: installed.append(import_name) or True,+ )+ ssm_runtime.ensure_ssm_runtime(name)+ assert installed == []++[email protected]("name", _ZOO_GDN_NAMES)+def test_zoo_kill_switch_brings_the_causal_conv1d_request_back(monkeypatch, name):+ monkeypatch.setenv(ssm_runtime.ZOO_TRITON_CAUSAL_CONV1D_KILL_SWITCH, "1")+ assert ssm_runtime.model_wants_causal_conv1d(name) is True+ assert ssm_runtime.model_is_ssm(name) is False+++ "config",+ [+ {"model_type": "qwen3_next", "architectures": ["Qwen3NextForCausalLM"]},+ {+ "model_type": "qwen3_5",+ "architectures": ["Qwen3_5ForConditionalGeneration"],+ "text_config": {"model_type": "qwen3_5_text"},+ "vision_config": {"model_type": "qwen3_5_vision"},+ },+ {+ "model_type": "qwen3_5_moe",+ "architectures": ["Qwen3_5MoeForConditionalGeneration"],+ "text_config": {"model_type": "qwen3_5_moe_text"},+ "vision_config": {"model_type": "qwen3_5_moe_vision"},+ },+ ],+ ids = ["qwen3_next", "qwen3_5", "qwen3_5_moe"],+)+def test_zoo_gdn_configs_resolve_to_no_causal_conv1d(monkeypatch, tmp_path, config):+ target = str(_write_config(tmp_path / "renamed", config))+ monkeypatch.delenv(ssm_runtime.ZOO_TRITON_CAUSAL_CONV1D_KILL_SWITCH, raising = False)+ assert ssm_runtime.model_config_wants_causal_conv1d(config) is False+ assert ssm_runtime.resolved_model_wants_causal_conv1d("acme/x", target, None) is False+ monkeypatch.setenv(ssm_runtime.ZOO_TRITON_CAUSAL_CONV1D_KILL_SWITCH, "1")+ assert ssm_runtime.model_config_wants_causal_conv1d(config) is True+++def test_a_config_mixing_a_zoo_gdn_type_with_another_hybrid_still_requests_it():+ config = {"model_type": "qwen3_5", "text_config": {"model_type": "lfm2"}}+ assert ssm_runtime.model_config_wants_causal_conv1d(config) is True+++ "name",+ ["tiiuae/Falcon-H1-0.5B", "nvidia/Nemotron-H-8B", "ibm-granite/granite-4.0-h-micro"],+)+def test_mamba2_hybrids_still_install_both_on_demand(monkeypatch, name):+ order = []+ monkeypatch.setattr(+ ssm_runtime,+ "_install_kernel",+ lambda *, import_name, **_: order.append(import_name) or True,+ )+ ssm_runtime.ensure_ssm_runtime(name)+ assert order == ["causal_conv1d", "mamba_ssm"]+++def test_zoo_gdn_model_types_match_unsloth_zoo():+ """Studio's list must equal the models unsloth-zoo's Triton conv patches."""+ import ast+ import importlib.util++ spec = importlib.util.find_spec("unsloth_zoo")+ if spec is None or spec.origin is None:+ pytest.skip("unsloth_zoo not installed")+ source_path = Path(spec.origin).parent / "temporary_patches" / "gdn_causal_conv1d.py"+ if not source_path.is_file():+ pytest.skip("this unsloth_zoo has no Triton causal conv")+ tree = ast.parse(source_path.read_text(encoding = "utf-8"))+ values = [+ node.value+ for node in ast.walk(tree)+ if isinstance(node, ast.Assign)+ and any(isinstance(t, ast.Name) and t.id == "_GDN_MODELING" for t in node.targets)+ ]+ assert len(values) == 1+ assert set(ast.literal_eval(values[0])) == ssm_runtime.ZOO_GDN_MODEL_TYPES+++# ── mamba-ssm resolved from the config, not only the name ─────────────────────+++ "name, model_type",+ [+ ("nvidia/NVIDIA-Nemotron-Nano-9B-v2", "nemotron_h"),+ ("ibm-granite/granite-4.0-tiny-preview", "granitemoehybrid"),+ ("acme/internal-hybrid", "falcon_h1"),+ ("acme/internal-hybrid", "bamba"),+ ("acme/internal-hybrid", "jamba"),+ ("acme/internal-hybrid", "zamba"),+ ("acme/internal-hybrid", "zamba2"),+ ("acme/internal-hybrid", "mamba"),+ ("acme/internal-hybrid", "mamba2"),+ ("acme/internal-hybrid", "falcon_mamba"),+ ],+)+def test_renamed_or_unlisted_ssm_models_resolve_from_their_config(tmp_path, name, model_type):+ target = str(_write_config(tmp_path / "ckpt", {"model_type": model_type}))+ assert ssm_runtime.resolved_model_is_ssm(name, target, None) is True+ # Every mamba-ssm model also wants causal-conv1d.+ assert ssm_runtime.resolved_model_wants_causal_conv1d(name, target, None) is True+ assert (+ ssm_runtime.resolved_model_wants_causal_conv1d(+ name, target, None, scan_modeling_source = False+ )+ is True+ )+++def test_a_nested_ssm_text_config_resolves_too(tmp_path):+ config = {"model_type": "some_vlm", "text_config": {"model_type": "nemotron_h"}}+ target = str(_write_config(tmp_path / "vlm", config))+ assert ssm_runtime.resolved_model_is_ssm("acme/x", target, None) is True+++def test_a_known_non_ssm_config_overrides_an_ssm_looking_name(tmp_path):+ target = str(_write_config(tmp_path / "llama", {"model_type": "llama"}))+ assert ssm_runtime.resolved_model_is_ssm("user/falcon-h1-style-llama", target, None) is False+++def test_no_config_falls_back_to_the_name(tmp_path):+ missing = str(tmp_path / "no-config")+ assert ssm_runtime.resolved_model_is_ssm("tiiuae/Falcon-H1-0.5B", missing, None) is True+ assert ssm_runtime.resolved_model_is_ssm("unsloth/Llama-3.2-1B", missing, None) is False+++def test_resolved_answers_override_the_name(monkeypatch):+ order = []+ monkeypatch.setattr(+ ssm_runtime,+ "_install_kernel",+ lambda *, import_name, **_: order.append(import_name) or True,+ )+ ssm_runtime.ensure_ssm_runtime("acme/renamed", wants_causal_conv1d = False, is_ssm = True)+ assert order == ["causal_conv1d", "mamba_ssm"]+ order.clear()+ ssm_runtime.ensure_ssm_runtime("tiiuae/Falcon-H1-0.5B", wants_causal_conv1d = False, is_ssm = False)+ assert order == []+++def test_the_mamba_ssm_failure_names_the_offline_remedy(monkeypatch):+ monkeypatch.setattr(ssm_runtime, "_install_kernel", lambda **k: False)+ with pytest.raises(RuntimeError, match = "unsloth install-kernels"):+ ssm_runtime.ensure_ssm_runtime("tiiuae/Falcon-H1-0.5B")+++# ── zoo's Triton conv only counts where it can run ────────────────────────────+++# The real (cached) platform check, captured before the autouse fixture replaces it.+_REAL_PLATFORM_USABLE = ssm_runtime._zoo_triton_platform_usable.__wrapped__+++ "platform, triton, torch_version, usable",+ [+ ("linux", True, "2.13.0", True),+ ("linux", True, "2.13.0+cu130", True),+ ("win32", True, "2.13.0+cu130", True),+ ("linux", True, "2.11.0+rocm7.1", False),+ ("win32", False, "2.13.0+cu130", False),+ ("darwin", True, "2.13.0", False),+ ("linux", True, None, False),+ ("linux", True, "2.13.0+cpu", False),+ ("win32", True, "2.13.0", False),+ ],+ ids = [+ "linux-pypi-cuda",+ "linux-cu130",+ "windows-triton",+ "rocm",+ "windows-no-triton",+ "macos",+ "no-torch",+ "cpu-torch",+ "windows-pypi-cpu",+ ],+)+def test_zoo_triton_conv_platform_check(monkeypatch, platform, triton, torch_version, usable):+ monkeypatch.setattr(ssm_runtime.sys, "platform", platform)+ monkeypatch.delitem(ssm_runtime.sys.modules, "torch", raising = False)+ real_find_spec = ssm_runtime.importlib.util.find_spec+ monkeypatch.setattr(+ ssm_runtime.importlib.util,+ "find_spec",+ lambda name, *a: (+ (object() if triton else None) if name == "triton" else real_find_spec(name, *a)+ ),+ )++ def _version(name):+ if torch_version is None:+ raise ssm_runtime.importlib.metadata.PackageNotFoundError(name)+ return torch_version++ monkeypatch.setattr(ssm_runtime.importlib.metadata, "version", _version)+ assert _REAL_PLATFORM_USABLE() is usable+++def test_zoo_triton_conv_platform_check_reads_an_imported_torch(monkeypatch):+ import types++ monkeypatch.setattr(ssm_runtime.sys, "platform", "linux")+ monkeypatch.setattr(ssm_runtime.importlib.util, "find_spec", lambda name, *a: object())+ fake = types.SimpleNamespace(version = types.SimpleNamespace(cuda = None, hip = "7.1"))+ monkeypatch.setitem(ssm_runtime.sys.modules, "torch", fake)+ assert _REAL_PLATFORM_USABLE() is False+ fake.version = types.SimpleNamespace(cuda = "13.0", hip = None)+ assert _REAL_PLATFORM_USABLE() is True++[email protected]("name", ["unsloth/Qwen3.5-2B", "Qwen/Qwen3-Next-80B-A3B"])+def test_qwen_keeps_causal_conv1d_where_zoo_triton_conv_cannot_run(monkeypatch, tmp_path, name):+ monkeypatch.setattr(ssm_runtime, "_zoo_triton_platform_usable", lambda: False)+ assert ssm_runtime.model_wants_causal_conv1d(name) is True+ config = {"model_type": "qwen3_5", "text_config": {"model_type": "qwen3_5_text"}}+ assert ssm_runtime.model_config_wants_causal_conv1d(config) is True+++def test_the_platform_check_is_not_run_for_unrelated_models(monkeypatch):+ def _boom():+ raise AssertionError("the platform check must not run for a non-Qwen model")++ monkeypatch.setattr(ssm_runtime, "_zoo_triton_platform_usable", _boom)+ assert ssm_runtime.model_wants_causal_conv1d("unsloth/Llama-3.2-1B") is False+ assert ssm_runtime.model_wants_causal_conv1d("LiquidAI/LFM2-1.2B") is True+++# ── in-process installs reach an already-imported transformers ────────────────+++def test_refresh_clears_the_gates_and_cached_misses(monkeypatch):+ import functools++ calls = {"n": 0}++ @functools.lru_cache+ def is_causal_conv1d_available():+ calls["n"] += 1+ return calls["n"] > 1++ import_utils = types.SimpleNamespace(is_causal_conv1d_available = is_causal_conv1d_available)+ module_type = type(sys)+ kernel_module = module_type("causal_conv1d")+ mapping = {"causal-conv1d": None, "mamba-ssm": None, "flash-attn": None, "x": kernel_module}+ hub_kernels = types.SimpleNamespace(_KERNEL_MODULE_MAPPING = mapping)+ monkeypatch.setitem(sys.modules, "transformers", types.SimpleNamespace())+ monkeypatch.setitem(sys.modules, "transformers.utils.import_utils", import_utils)+ monkeypatch.setitem(sys.modules, "transformers.integrations.hub_kernels", hub_kernels)++ assert is_causal_conv1d_available() is False+ ssm_runtime.refresh_transformers_kernel_gates()+ assert is_causal_conv1d_available() is True+ assert mapping == {"flash-attn": None, "x": kernel_module}+++def test_refresh_is_a_no_op_without_transformers_and_never_raises(monkeypatch):+ monkeypatch.delitem(sys.modules, "transformers", raising = False)+ ssm_runtime.refresh_transformers_kernel_gates()++ class _Broken:+ def __getattr__(self, name):+ raise RuntimeError("boom")++ monkeypatch.setitem(sys.modules, "transformers", types.SimpleNamespace())+ monkeypatch.setitem(sys.modules, "transformers.utils.import_utils", _Broken())+ monkeypatch.setitem(sys.modules, "transformers.integrations.hub_kernels", _Broken())+ ssm_runtime.refresh_transformers_kernel_gates()+++def test_inference_worker_resolves_kernels_from_the_base_config(monkeypatch, tmp_path):+ from core.inference import worker as iw++ target = str(_write_config(tmp_path / "renamed", {"model_type": "nemotron_h"}))+ seen = []+ monkeypatch.setattr(+ ssm_runtime,+ "ensure_ssm_runtime",+ lambda probe, **kwargs: seen.append(+ (probe, kwargs["wants_causal_conv1d"], kwargs["is_ssm"])+ ),+ )+ refreshed = []+ monkeypatch.setattr(+ ssm_runtime, "refresh_transformers_kernel_gates", lambda: refreshed.append(1)+ )+ assert iw._ensure_ssm_kernels([("renamed", target)], resp_queue = None, hf_token = None)+ assert seen == [("renamed", True, True)]+ assert refreshed == [1]++ src = (_BACKEND / "core" / "inference" / "worker.py").read_text(encoding = "utf-8")+ assert "_ensure_ssm_kernels(ssm_targets, resp_queue, hf_token)" in src+ assert "_ensure_ssm_kernels(_ssm_targets, resp_queue, _hf_token)" in srcdiff --git a/studio/backend/tests/test_training_worker_flash_attn.py b/studio/backend/tests/test_training_worker_flash_attn.pyindex 87012b042e8..08993cf03ea 100644--- a/studio/backend/tests/test_training_worker_flash_attn.py+++ b/studio/backend/tests/test_training_worker_flash_attn.py@@ -603,19 +603,40 @@ def test_causal_conv1d_fast_path_preserves_wheel_first_install_args(monkeypatch)@not_on_windows-def test_causal_conv1d_fast_path_includes_qwen3_6_variants(monkeypatch):+def test_causal_conv1d_fast_path_skips_qwen3_6_variants_on_zoo_triton_conv(monkeypatch):+ # unsloth-zoo runs Qwen3.5 / 3.6 / Qwen3-Next on its own Triton causal conv (on a CUDA torch+ # with Triton, pinned here so a CPU-only CI host answers the same).+ from utils import ssm_runtime+install_mock = mock.Mock(return_value = True)monkeypatch.setattr(worker, "_install_package_wheel_first", install_mock)+ monkeypatch.setattr(ssm_runtime, "_zoo_triton_platform_usable", lambda: True)+ monkeypatch.delenv("UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D", raising = False)- worker._ensure_causal_conv1d_fast_path(- event_queue = [],- model_name = "unsloth/Qwen3.6-4B",- )- worker._ensure_causal_conv1d_fast_path(- event_queue = [],- model_name = "unsloth/Qwen3_6-4B",- )+ for model_name in ("unsloth/Qwen3.6-4B", "unsloth/Qwen3_6-4B"):+ worker._ensure_causal_conv1d_fast_path(event_queue = [], model_name = model_name)+ assert install_mock.call_count == 0+ # zoo's kill switch puts them back on the prebuilt causal-conv1d.+ monkeypatch.setenv("UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D", "1")+ for model_name in ("unsloth/Qwen3.6-4B", "unsloth/Qwen3_6-4B"):+ worker._ensure_causal_conv1d_fast_path(event_queue = [], model_name = model_name)+ assert install_mock.call_count == 2+++def test_mamba_ssm_follows_the_resolved_answer_not_the_name(monkeypatch):+ install_mock = mock.Mock(return_value = True)+ monkeypatch.setattr(worker, "_install_package_wheel_first", install_mock)+ # A real hybrid whose id lacks the substrings (resolved from its config) still installs.+ worker._ensure_mamba_ssm(+ event_queue = [], model_name = "nvidia/NVIDIA-Nemotron-Nano-9B-v2", required = True+ )+ assert install_mock.call_count == 1+ # A config that says otherwise wins over an SSM-looking name.+ worker._ensure_mamba_ssm(event_queue = [], model_name = "tiiuae/Falcon-H1-0.5B", required = False)+ assert install_mock.call_count == 1+ # The Mamba-1 family is detected by name now as well.+ worker._ensure_mamba_ssm(event_queue = [], model_name = "ai21labs/Jamba-v0.1")assert install_mock.call_count == 2@@ -1498,7 +1519,7 @@ def test_windows_causal_conv1d_fast_path_installs(monkeypatch):_as_windows(monkeypatch)install_mock = mock.Mock(return_value = True)monkeypatch.setattr(worker, "_install_package_wheel_first", install_mock)- worker._ensure_causal_conv1d_fast_path(event_queue = [], model_name = "unsloth/Qwen3.6-4B")+ worker._ensure_causal_conv1d_fast_path(event_queue = [], model_name = "LiquidAI/LFM2-1.2B")install_mock.assert_called_once()diff --git a/studio/backend/utils/kernel_install.py b/studio/backend/utils/kernel_install.pyindex 364f90c2fd6..f3bb2ee6039 100644--- a/studio/backend/utils/kernel_install.py+++ b/studio/backend/utils/kernel_install.py@@ -328,14 +328,12 @@ def install_kernel(dry_run: bool = False,run: Callable[..., subprocess.CompletedProcess] = subprocess.run,exists: Callable[[str], bool | None] = url_exists,- install_without_gpu: bool = False,) -> int:- # install_without_gpu (setup): no visible GPU yet, e.g. an image build, still installs.distribution, check = KERNELS[name]url = resolve_wheel_url(name, env)if name in _GPU_GATED and url is not None:capability = _gpu_capability(run)- if capability is None and not install_without_gpu:+ if capability is None:print(f"Unsloth: skipping {name}, which needs sm80 or newer (no CUDA GPU is visible).")return 0if capability is not None and capability < (8, 0):diff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.pyindex db6d2e65b87..e85bcecfd8c 100644--- a/studio/backend/utils/ssm_runtime.py+++ b/studio/backend/utils/ssm_runtime.py@@ -7,7 +7,9 @@ the inference-path counterpart of the training worker's install.from __future__ import annotations+import functoolsimport importlib+import importlib.metadataimport importlib.utilimport osimport shutil@@ -50,14 +52,29 @@ SSM_MODEL_SUBSTRINGS = ("falcon-h1","granite-4.0-h","granitemoehybrid",+ "mamba",+ "jamba",+ "zamba",+ "bamba",+)+# config.json model types whose modeling files run mamba_ssm (and so causal_conv1d): Mamba-2+# hybrids and the Mamba-1 family. Matched on the resolved config, so a renamed checkpoint or an+# id without the substrings above (NVIDIA-Nemotron-Nano-9B-v2, granite-4.0-tiny) still counts.+SSM_MODEL_TYPES = frozenset(+ {+ "nemotron_h",+ "falcon_h1",+ "granitemoehybrid",+ "bamba",+ "jamba",+ "zamba",+ "zamba2",+ "mamba",+ "mamba2",+ "falcon_mamba",+ })CAUSAL_CONV1D_MODEL_SUBSTRINGS = (- "qwen3.5",- "qwen3_5",- "qwen3.6",- "qwen3_6",- "qwen3-next",- "qwen3_next","nemotron_h","nemotron-h","nemotron-3-nano",@@ -71,9 +88,71 @@ CAUSAL_CONV1D_MODEL_SUBSTRINGS = ("zamba","bamba",)+# GatedDeltaNet models unsloth-zoo runs without causal_conv1d: its Triton causal conv+# (temporary_patches/gdn_causal_conv1d.py, `_GDN_MODELING`) plus the vendored FLA kernels. Qwen3.6+# reuses the qwen3_5 model types. A usable causal_conv1d still wins inside zoo; this only stops+# Studio from downloading it. Zoo's own kill switch brings the request back.+ZOO_GDN_MODEL_TYPES = frozenset({"qwen3_5", "qwen3_5_moe", "qwen3_next"})+ZOO_GDN_MODEL_SUBSTRINGS = (+ "qwen3.5",+ "qwen3_5",+ "qwen3.6",+ "qwen3_6",+ "qwen3-next",+ "qwen3_next",+)+ZOO_TRITON_CAUSAL_CONV1D_KILL_SWITCH = "UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D"_TRANSFORMERS_CAUSAL_CONV1D_MODEL_TYPE_CACHE: dict[str, bool | None] = {}+def zoo_triton_causal_conv1d_enabled() -> bool:+ return os.environ.get(ZOO_TRITON_CAUSAL_CONV1D_KILL_SWITCH, "0") != "1"++[email protected]_cache(maxsize = 1)+def _zoo_triton_platform_usable() -> bool:+ """Whether zoo's Triton conv can engage here: a CUDA torch (not ROCm) with Triton importable.+ macOS, ROCm and a Windows install without triton-windows keep the prebuilt causal-conv1d.+ Read from torch's distribution version, so no model load pays for importing torch: ROCm and+ CPU builds carry `+rocm` / `+cpu`, a Windows CUDA build `+cu`, and a Linux PyPI torch with no+ local version is the CUDA build."""+ if sys.platform == "darwin" or importlib.util.find_spec("triton") is None:+ return False+ torch = sys.modules.get("torch")+ if torch is not None:+ version = getattr(torch, "version", None)+ return bool(getattr(version, "cuda", None)) and not getattr(version, "hip", None)+ try:+ local = importlib.metadata.version("torch").partition("+")[2].lower()+ except importlib.metadata.PackageNotFoundError:+ return False+ if local.startswith(("rocm", "cpu")):+ return False+ return local.startswith("cu") or (not local and sys.platform.startswith("linux"))+++def zoo_triton_causal_conv1d_usable() -> bool:+ """zoo runs Qwen3.5 / 3.6 / Qwen3-Next without causal_conv1d on this host."""+ return zoo_triton_causal_conv1d_enabled() and _zoo_triton_platform_usable()+++def _base_model_type(model_type: str) -> str:+ """A config's model type with its `_text` / `_vision` sub-config suffix removed."""+ candidate = model_type.strip().lower().replace("-", "_")+ for suffix in ("_text", "_vision"):+ candidate = candidate.removesuffix(suffix)+ return candidate+++def _is_zoo_gdn_model_type(model_type: str) -> bool:+ """The model type or one of its `_text` / `_vision` sub-configs belongs to a zoo-covered model."""+ return _base_model_type(model_type) in ZOO_GDN_MODEL_TYPES+++def _names_zoo_gdn_model(name: str) -> bool:+ return any(sub in name for sub in ZOO_GDN_MODEL_SUBSTRINGS)++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()@@ -81,9 +160,11 @@ def model_is_ssm(model_name: str) -> bool: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)."""+ """Whether *model_name* needs ``causal_conv1d`` (the SSM set plus linear-attention hybrids like LFM2 whose modeling files lazy-import it; Qwen3.5 / 3.6 / Qwen3-Next only where zoo's Triton conv cannot run)."""name = (model_name or "").lower()- return any(sub in name for sub in CAUSAL_CONV1D_MODEL_SUBSTRINGS)+ if any(sub in name for sub in CAUSAL_CONV1D_MODEL_SUBSTRINGS):+ return True+ return _names_zoo_gdn_model(name) and not zoo_triton_causal_conv1d_usable()def _normalized_model_identifier(value: str) -> str:@@ -123,7 +204,8 @@ def _transformers_model_type_uses_causal_conv1d(model_type: str) -> bool | None:return result-def model_config_wants_causal_conv1d(model_config: dict) -> bool | None:+def _config_identifiers(model_config: dict) -> tuple[set[str], set[str]]:+ """Every model_type and architecture in *model_config*, nested sub-configs included."""model_types: set[str] = set()architectures: set[str] = set()pending: list[Any] = [model_config]@@ -143,39 +225,72 @@ def model_config_wants_causal_conv1d(model_config: dict) -> bool | None:pending.extend(value.values())elif isinstance(value, (list, tuple)):pending.extend(value)+ return model_types, architectures- source_requirements = {- _transformers_model_type_uses_causal_conv1d(model_type) for model_type in model_types- }++def model_config_is_ssm(model_config: dict) -> bool | None:+ """True for a Mamba-family model type, False for another known type, None without one."""+ model_types, _ = _config_identifiers(model_config)+ if not model_types:+ return None+ return any(_base_model_type(model_type) in SSM_MODEL_TYPES for model_type in model_types)+++def model_config_wants_causal_conv1d(+ model_config: dict, *, scan_modeling_source: bool = True+) -> bool | None:+ """``scan_modeling_source=False`` keeps the answer transformers-free (the inference worker asks+ before its transformers import, which snapshots the kernel gates)."""+ model_types, architectures = _config_identifiers(model_config)+ if model_config_is_ssm(model_config):+ return True+ if model_types and all(_is_zoo_gdn_model_type(model_type) for model_type in model_types):+ return not zoo_triton_causal_conv1d_usable()+ source_requirements = (+ {_transformers_model_type_uses_causal_conv1d(model_type) for model_type in model_types}+ if scan_modeling_source+ else set()+ )if True in source_requirements:return Trueconfig_identifiers = model_types | architectures- normalized_needles = {- _normalized_model_identifier(value) for value in CAUSAL_CONV1D_MODEL_SUBSTRINGS- }- if any(- needle in _normalized_model_identifier(identifier)- for identifier in config_identifiers- for needle in normalized_needles- ):+ normalized = {_normalized_model_identifier(identifier) for identifier in config_identifiers}++ def _matches(substrings: tuple[str, ...]) -> bool:+ needles = {_normalized_model_identifier(value) for value in substrings}+ return any(needle in identifier for identifier in normalized for needle in needles)++ if _matches(CAUSAL_CONV1D_MODEL_SUBSTRINGS):+ return True+ if _matches(ZOO_GDN_MODEL_SUBSTRINGS) and not zoo_triton_causal_conv1d_usable():return Trueif False in source_requirements:return Falsereturn None-def resolved_model_wants_causal_conv1d(- model_name: str, model_load_target: str, hf_token: str | None-) -> bool:+def _resolved_model_config(model_load_target: str, hf_token: str | None) -> dict | None:try:from utils.transformers_version import _load_config_jsonmodel_config = _load_config_json(model_load_target, hf_token)except Exception as exc:- logger.debug("Could not inspect model config for causal-conv1d: %s", exc)- model_config = None+ logger.debug("Could not inspect model config for SSM kernels: %s", exc)+ return None+ return model_config if isinstance(model_config, dict) else None- if isinstance(model_config, dict):- requirement = model_config_wants_causal_conv1d(model_config)++def resolved_model_wants_causal_conv1d(+ model_name: str,+ model_load_target: str,+ hf_token: str | None,+ *,+ scan_modeling_source: bool = True,+) -> bool:+ model_config = _resolved_model_config(model_load_target, hf_token)+ if model_config is not None:+ requirement = model_config_wants_causal_conv1d(+ model_config, scan_modeling_source = scan_modeling_source+ )if requirement is not None:logger.info("causal-conv1d requirement resolved from model architecture: %s",@@ -185,6 +300,48 @@ def resolved_model_wants_causal_conv1d(return model_wants_causal_conv1d(model_name)+def resolved_model_is_ssm(model_name: str, model_load_target: str, hf_token: str | None) -> bool:+ """Whether the model at *model_load_target* needs ``mamba_ssm``, from its config; the name list+ only when there is no config to read."""+ model_config = _resolved_model_config(model_load_target, hf_token)+ if model_config is not None:+ requirement = model_config_is_ssm(model_config)+ if requirement is not None:+ logger.info("mamba-ssm requirement resolved from model architecture: %s", requirement)+ return requirement+ return model_is_ssm(model_name)+++def refresh_transformers_kernel_gates() -> None:+ """After an in-process install, let an already-imported transformers see the new kernels: its+ availability gates are lru_cached and the hub-kernel map can hold a cached None. Never raises."""+ if "transformers" not in sys.modules:+ return+ try:+ import_utils = sys.modules.get("transformers.utils.import_utils")+ for gate_name in (+ "is_causal_conv1d_available",+ "is_mamba_ssm_available",+ "is_mamba_2_ssm_available",+ ):+ cache_clear = getattr(getattr(import_utils, gate_name, None), "cache_clear", None)+ if callable(cache_clear):+ cache_clear()+ except Exception as exc:+ logger.debug("Could not clear transformers' kernel gates: %s", exc)+ try:+ hub_kernels = sys.modules.get("transformers.integrations.hub_kernels")+ mapping = getattr(hub_kernels, "_KERNEL_MODULE_MAPPING", None)+ if isinstance(mapping, dict):+ for key in [key for key, value in mapping.items() if value is None]:+ if any(+ kernel in str(key) for kernel in ("causal-conv1d", "causal_conv1d", "mamba")+ ):+ mapping.pop(key, None)+ except Exception as exc:+ logger.debug("Could not refresh transformers' hub kernel map: %s", exc)++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@@ -393,10 +550,17 @@ def ensure_ssm_runtime(*,status_cb: StatusCb = None,run: Callable[..., Any] = subprocess.run,+ wants_causal_conv1d: bool | None = None,+ is_ssm: bool | None = None,) -> 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, with Qwen3-Next/LFM2 falling back to torch."""- wants_causal_conv1d = model_wants_causal_conv1d(model_name)- is_ssm = model_is_ssm(model_name)+ """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, with LFM2 falling back to torch and Qwen3.5 / 3.6 / Qwen3-Next on zoo's Triton conv wherever it can run."""+ # The caller's config-resolved answers win; the name match is the default.+ if is_ssm is None:+ is_ssm = model_is_ssm(model_name)+ if wants_causal_conv1d is None:+ wants_causal_conv1d = model_wants_causal_conv1d(model_name)+ # Every mamba-ssm model also runs causal-conv1d.+ wants_causal_conv1d = wants_causal_conv1d or is_ssmif not (wants_causal_conv1d or is_ssm):return@@ -413,4 +577,7 @@ def ensure_ssm_runtime("(the triton-windows package); install it and reload the model.")if is_ssm and not _install_kernel(**_pinned_kwargs(MAMBA_SSM), status_cb = status_cb, run = run):- raise RuntimeError("Could not install mamba-ssm, required by this Mamba model.")+ raise RuntimeError(+ "Could not install mamba-ssm, required by this Mamba model. If this machine is offline, "+ "run `unsloth install-kernels` once while online, then reload the model."+ )diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 56f17b39b28..bd3b1c96305 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -12,12 +12,10 @@ activated. Expects `pip` and `python` on PATH to point at the venv.from __future__ import annotationsimport ast-import contextlibimport functoolsimport globimport importlibimport importlib.util-import ioimport jsonimport localeimport os@@ -54,8 +52,6 @@ def _nvidia_library_inventory():from backend.utils.kernel_install import (- KERNELS,- install_kernel,install_prebuilt,uninstall_command,)@@ -8600,89 +8596,6 @@ def _ensure_flash_attn() -> None:_remove_stale_flash_attn()-def _ssm_kernel_install_disabled() -> bool:- return os.getenv("UNSLOTH_STUDIO_SKIP_SSM_KERNELS_INSTALL") == "1"---def _ensure_ssm_kernels() -> None:- """causal-conv1d and mamba-ssm prebuilt wheels at setup, via the wheel-only install_kernel."""- if _ssm_kernel_install_disabled() or NO_TORCH or IS_MACOS:- return- # Bounded on every platform, and a probe that cannot launch skips this optional step.- try:- env = probe_torch_wheel_env(timeout = _FLASH_ATTN_IMPORT_PROBE_TIMEOUT, include_windows = True)- except OSError:- return- if env is None:- return-- # A new runner per call resets install_kernel's per-runner GPU / Triton cache after a torch- # repair; it bounds import probes, not installs.- def run(cmd, *args, **kwargs):- if list(cmd[:2]) == [sys.executable, "-c"]:- kwargs.setdefault("timeout", _FLASH_ATTN_IMPORT_PROBE_TIMEOUT)- return subprocess.run(cmd, *args, **kwargs)-- def loads(check: str) -> bool | None:- try:- return (- run(- [sys.executable, "-c", check],- stdout = subprocess.DEVNULL,- stderr = subprocess.DEVNULL,- ).returncode- == 0- )- except (subprocess.TimeoutExpired, OSError):- return None-- for name in ("causal_conv1d", "mamba_ssm"):- distribution, check = KERNELS[name]- installed = _installed_distribution_version(distribution) is not None- # Local first, so an offline re-run does not wait on a wheel HEAD request.- if installed and loads(check):- _note(f"{name} already installed and loads.")- continue- status = 0- buffer = io.StringIO()- if _uv_is_offline():- # install_wheel's pip fallback ignores UV_OFFLINE; stale removal below still runs.- if not installed:- _note(- f"{name} not installed: UV_OFFLINE is set; run `unsloth install-kernels` online"- )- else:- try:- with contextlib.redirect_stdout(buffer):- status = install_kernel(name, env, run = run, install_without_gpu = True)- except Exception as exc:- status = 1- buffer.write(f"{type(exc).__name__}: {exc}")- # install_kernel redacts only the wheel URL; uv / pip failure text can name another index.- for line in _redact_install_output(buffer.getvalue()).splitlines():- if line.strip():- _note(line.removeprefix("Unsloth: "))- if status or f"Unsloth: installed {name} " in buffer.getvalue():- _count_install_action()- if _installed_distribution_version(distribution) is not None and loads(check) is False:- _count_install_action()- try:- removed = _uninstall_distribution(distribution)- except OSError:- removed = False- if removed:- _step("warning", f"{name} does not load with this torch; removed it", _warn)- else:- _step(- "warning",- f"{name} does not load with this torch and could not be removed; "- f"uninstall {distribution} manually",- _warn,- )- elif status:- _step("warning", f"Continuing without {name}", _warn)--# -- uv bootstrap ------------------------------------------------------USE_UV = False # Set by _bootstrap_uv() at the start of install_python_stack()@@ -12420,7 +12333,6 @@ def install_python_stack() -> int:if not IS_MACOS and not NO_TORCH:base_total += 1 # ROCm torch check (step 2b), non-macOSbase_total += 1 # flash-attn, Linux and Windows- base_total += 1 # causal-conv1d + mamba-ssm, same gateif not IS_WINDOWS:base_total += 1 # torch final repair (step 13), Linuxelse:@@ -12831,8 +12743,6 @@ def install_python_stack() -> int:if not IS_MACOS and not NO_TORCH:_progress("flash-attn")_ensure_flash_attn()- _progress("mamba kernels")- _ensure_ssm_kernels()# # 6. Patch: override llama_cpp.py with fix from unsloth-zoo feature/llama-cpp-windows-support branch# patch_package_file(@@ -13016,9 +12926,8 @@ def install_python_stack() -> int:"flash-attn")_install_torchao_for_torch(_torch_after_repair)- # resync the kernels because the repair can invalidate the wheels selected earlier.+ # resync flash-attn because the repair can invalidate the wheel selected earlier._ensure_flash_attn()- _ensure_ssm_kernels()# Unguarded: torch==2.10.0 accepts 2.10.0+rocm7.1, and an earlier run may have moved it._evict_xformers_built_for_another_torch(scope = "linux torch repair", family_only = True)_evict_xformers_requiring_another_torch()@@ -13033,9 +12942,8 @@ def install_python_stack() -> int:return 1_torch_after_flavor = str(_probe_installed_torch_version() or "")if _torch_after_flavor and _torch_after_flavor != _torch_before_flavor:- # The kernels were chosen for the torch the invariant just replaced, as in step 13.+ # flash-attn was chosen for the torch the invariant just replaced, as in step 13._ensure_flash_attn()- _ensure_ssm_kernels()# A direct run has no setup.ps1 postlude to swap triton back. After the invariant,# because the swap keys off the installed +xpu label._ensure_xpu_triton()diff --git a/tests/python/test_ssm_kernels_install_python_stack.py b/tests/python/test_ssm_kernels_install_python_stack.pyindex ee385104c4c..a25c192fb83 100644--- a/tests/python/test_ssm_kernels_install_python_stack.py+++ b/tests/python/test_ssm_kernels_install_python_stack.py@@ -1,19 +1,16 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Setup installs causal-conv1d and mamba-ssm prebuilt wheels next to flash-attn, so a Mamba /-hybrid model does not wait on a download at load time."""+"""Setup installs flash-attn but not causal-conv1d or mamba-ssm: those (~550 MB) install when a+model that needs them is trained or loaded (core/training/worker.py, utils/ssm_runtime.py), and+`unsloth install-kernels` still provisions them ahead of time for offline images."""from __future__ import annotations+import astimport re-import subprocessimport sysfrom pathlib import Path-from types import SimpleNamespace-from unittest import mock--import pytestSTUDIO_DIR = Path(__file__).resolve().parents[2] / "studio"sys.path.insert(0, str(STUDIO_DIR))@@ -22,254 +19,34 @@ sys.path.insert(0, str(STUDIO_DIR / "backend"))import install_python_stack as ips # noqa: E402SOURCE = (STUDIO_DIR / "install_python_stack.py").read_text(encoding = "utf-8")-ENV = {"platform_tag": "linux_x86_64", "torch_mm": "2.13", "torch_version": "2.13.0+cu130"}-DISTS = {"causal_conv1d": "causal-conv1d", "mamba_ssm": "mamba-ssm"}---class _Host:- """Which kernels are installed and whether they import; the fake install_kernel edits it."""-- def __init__(- self,- installed = (),- loading = (),- hangs = (),- unlaunchable = (),- ):- self.installed = set(installed)- self.loading = set(loading)- self.hangs = set(hangs)- self.unlaunchable = set(unlaunchable)- self.timeouts = []-- def version(self, distribution):- return "1.0" if distribution in self.installed else None-- def run(self, cmd, *args, **kwargs):- self.timeouts.append(kwargs.get("timeout"))- for name, distribution in DISTS.items():- if cmd[-1] == ips.KERNELS[name][1]:- if distribution in self.hangs:- raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout"))- if distribution in self.unlaunchable:- raise PermissionError(13, "Access is denied")- return SimpleNamespace(returncode = 0 if distribution in self.loading else 1)- return SimpleNamespace(returncode = 0)---def _run(- host,- install_kernel,- *,- env = ENV,- no_torch = False,- macos = False,- disabled = False,- offline = False,-):- steps, notes = [], []- with (- mock.patch.object(ips, "NO_TORCH", no_torch),- mock.patch.object(ips, "IS_MACOS", macos),- mock.patch.object(ips, "IS_WINDOWS", False),- mock.patch.object(ips, "_uv_is_offline", return_value = offline),- mock.patch.object(ips, "probe_torch_wheel_env", return_value = env) as probe,- mock.patch.object(ips, "install_kernel", side_effect = install_kernel) as kernel,- mock.patch.object(ips, "_installed_distribution_version", side_effect = host.version),- mock.patch.object(ips.subprocess, "run", side_effect = host.run),- mock.patch.object(- ips, "_uninstall_distribution", side_effect = lambda d: host.installed.discard(d) or True- ) as uninstall,- mock.patch.object(ips, "_count_install_action") as counted,- mock.patch.object(ips, "_step", side_effect = lambda label, value, *_: steps.append(value)),- mock.patch.object(ips, "_note", side_effect = lambda message, *_: notes.append(message)),- mock.patch.dict(- "os.environ", {"UNSLOTH_STUDIO_SKIP_SSM_KERNELS_INSTALL": "1" if disabled else ""}- ),- ):- ips._ensure_ssm_kernels()- return SimpleNamespace(- kernel = kernel,- probe = probe,- uninstall = uninstall,- counted = counted,- steps = steps,- notes = notes,- )---def _installer(host):- def install(name, env, **kwargs):- print(f"Unsloth: installed {name} ({name}-x.whl).")- host.installed.add(DISTS[name])- host.loading.add(DISTS[name])- return 0-- return install---def test_both_kernels_install_for_the_resident_torch():- host = _Host()- r = _run(host, _installer(host))- assert [c.args for c in r.kernel.call_args_list] == [("causal_conv1d", ENV), ("mamba_ssm", ENV)]- for call in r.kernel.call_args_list:- assert call.kwargs["install_without_gpu"] is True- assert r.probe.call_args.kwargs["include_windows"] is True- assert r.counted.call_count == 2- assert r.steps == [] and r.uninstall.call_count == 0- assert r.notes == [- "installed causal_conv1d (causal_conv1d-x.whl).",- "installed mamba_ssm (mamba_ssm-x.whl).",- ]---def test_a_kernel_that_already_loads_is_not_looked_up_online():- host = _Host(installed = DISTS.values(), loading = DISTS.values())- r = _run(host, _installer(host))- assert r.kernel.call_count == 0 and r.counted.call_count == 0- assert r.notes == [- "causal_conv1d already installed and loads.",- "mamba_ssm already installed and loads.",- ]---def test_a_resident_build_that_no_longer_loads_is_removed_when_nothing_replaces_it():- host = _Host(installed = DISTS.values())-- def no_wheel(name, env, **kwargs):- print(f"Unsloth: no prebuilt {name} for torch 2.15.0; using the torch fallback.")- return 0-- r = _run(host, no_wheel)- assert [c.args[0] for c in r.uninstall.call_args_list] == ["causal-conv1d", "mamba-ssm"]- assert r.steps == [- "causal_conv1d does not load with this torch; removed it",- "mamba_ssm does not load with this torch; removed it",- ]---def test_offline_mode_neither_looks_up_nor_installs_but_keeps_what_loads():- host = _Host(installed = ["causal-conv1d"], loading = ["causal-conv1d"])- r = _run(host, _installer(host), offline = True)- assert r.kernel.call_count == 0 and r.uninstall.call_count == 0- assert r.notes == [- "causal_conv1d already installed and loads.",- "mamba_ssm not installed: UV_OFFLINE is set; run `unsloth install-kernels` online",- ]-+TREE = ast.parse(SOURCE)-def test_offline_still_removes_a_resident_build_that_no_longer_loads():- host = _Host(installed = ["mamba-ssm"])- r = _run(host, _installer(host), offline = True)- assert r.kernel.call_count == 0- assert [c.args[0] for c in r.uninstall.call_args_list] == ["mamba-ssm"]+def _called_names() -> set[str]:+ return {+ node.func.id+ for node in ast.walk(TREE)+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)+ }-def test_a_probe_that_cannot_be_launched_is_inconclusive_not_fatal():- host = _Host(installed = ["mamba-ssm"], unlaunchable = ["mamba-ssm"])- r = _run(host, lambda name, env, **kwargs: 0)- assert r.kernel.call_count == 2 and r.uninstall.call_count == 0+def test_setup_has_no_ssm_kernel_step():+ assert not hasattr(ips, "_ensure_ssm_kernels")+ assert "install_kernel" not in _called_names()+ assert '_progress("mamba kernels")' not in SOURCE+ assert "causal-conv1d + mamba-ssm" not in SOURCE-def test_the_torch_probe_is_bounded_everywhere_and_a_launch_failure_skips_the_step():- host = _Host()- r = _run(host, _installer(host))- assert r.probe.call_args.kwargs["timeout"] == ips._FLASH_ATTN_IMPORT_PROBE_TIMEOUT- with mock.patch.object(ips, "probe_torch_wheel_env", side_effect = OSError("no fork")):- with mock.patch.object(ips, "install_kernel") as kernel:- ips._ensure_ssm_kernels()- assert kernel.call_count == 0--def test_an_uninstall_that_cannot_launch_warns_instead_of_aborting():- host = _Host(installed = DISTS.values())- with mock.patch.object(ips, "_uninstall_distribution", side_effect = OSError("no fork")):- steps = []- with (- mock.patch.object(ips, "NO_TORCH", False),- mock.patch.object(ips, "IS_MACOS", False),- mock.patch.object(ips, "_uv_is_offline", return_value = True),- mock.patch.object(ips, "probe_torch_wheel_env", return_value = ENV),- mock.patch.object(ips, "_installed_distribution_version", side_effect = host.version),- mock.patch.object(ips.subprocess, "run", side_effect = host.run),- mock.patch.object(ips, "_count_install_action"),- mock.patch.object(ips, "_note"),- mock.patch.object(- ips, "_step", side_effect = lambda label, value, *_: steps.append(value)- ),- ):- ips._ensure_ssm_kernels()- assert steps == [- "causal_conv1d does not load with this torch and could not be removed; "- "uninstall causal-conv1d manually",- "mamba_ssm does not load with this torch and could not be removed; "- "uninstall mamba-ssm manually",- ]---def test_captured_failure_text_is_redacted():- host = _Host()-- def leaks(name, env, **kwargs):- raise RuntimeError("index https://user:[email protected]/simple?token=abc failed")-- r = _run(host, leaks)- joined = "\n".join(r.notes)- assert "s3cret" not in joined and "token=abc" not in joined- assert "<redacted>" in joined---def test_a_failure_warns_and_the_next_kernel_still_runs():- host = _Host()- install = _installer(host)-- def first_fails(name, env, **kwargs):- if name == "causal_conv1d":- raise OSError("disk full")- return install(name, env, **kwargs)-- r = _run(host, first_fails)- assert r.kernel.call_count == 2- assert r.steps == ["Continuing without causal_conv1d"]- assert "OSError: disk full" in r.notes---def test_a_hung_import_probe_is_bounded_and_never_read_as_broken():- host = _Host(installed = ["mamba-ssm"], hangs = ["mamba-ssm"])- r = _run(host, lambda name, env, **kwargs: 0)- assert r.uninstall.call_count == 0- assert host.timeouts- assert all(t == ips._FLASH_ATTN_IMPORT_PROBE_TIMEOUT for t in host.timeouts)---def test_each_call_gets_a_fresh_runner_so_a_repaired_torch_is_probed_again():- runners = []-- def record(name, env, **kwargs):- runners.append(kwargs["run"])- return 0-- _run(_Host(), record)- _run(_Host(), record)- assert runners[0] is runners[1] and runners[2] is runners[3]- assert runners[0] is not runners[2]--- "kwargs",- [{"no_torch": True}, {"macos": True}, {"disabled": True}, {"env": None}],- ids = ["no-torch", "macos", "opted-out", "no-cuda-torch"],-)-def test_nothing_is_installed_when_it_cannot_apply(kwargs):- host = _Host()- r = _run(host, _installer(host), **kwargs)- assert r.kernel.call_count == 0---def test_every_flash_attn_site_also_resyncs_the_ssm_kernels():+def test_flash_attn_is_still_installed_and_resynced_at_all_three_sites():calls = [m.start() for m in re.finditer(r"\n\s+_ensure_flash_attn\(\)\n", SOURCE)]assert len(calls) == 3for start in calls:following = SOURCE[start : start + 200]- assert "_ensure_ssm_kernels()" in following, following- assert "base_total += 1 # causal-conv1d + mamba-ssm, same gate" in SOURCE+ assert "ssm" not in following.lower(), following+ assert "base_total += 1 # flash-attn, Linux and Windows" in SOURCE+++def test_the_kernel_cli_still_provisions_both_ahead_of_time():+ from utils import kernel_install+ assert {"causal_conv1d", "mamba_ssm"} <= set(kernel_install.KERNELS)+ assert callable(kernel_install.install_kernel)diff --git a/tests/studio/install/test_windows_torch_flavor_invariant.py b/tests/studio/install/test_windows_torch_flavor_invariant.pyindex 95fcda86687..413c66bdc8e 100644--- a/tests/studio/install/test_windows_torch_flavor_invariant.py+++ b/tests/studio/install/test_windows_torch_flavor_invariant.py@@ -252,13 +252,13 @@ class TestStepThirteenWiring:assert calls[:2] == ["_progress", "_torch_step_label"]# str() coerces the probe label and does not represent a step.step13 = [c for c in _calls_in(guards[1]) if c != "str"]- # repairs refresh torchao and flash-attn for final torch (#13244), then causal-conv1d and- # mamba-ssm (#13396), then evict incompatible xFormers (#11545).+ # repairs refresh torchao and flash-attn for final torch (#13244), then evict incompatible+ # xFormers (#11545). causal-conv1d and mamba-ssm install when a model needs them, not here.assert step13 == (["_progress", "_torch_step_label", "_probe_installed_torch_version"]+ repairs+ ["_probe_installed_torch_version", "_note", "_install_torchao_for_torch"]- + ["_ensure_flash_attn", "_ensure_ssm_kernels"]+ + ["_ensure_flash_attn"]+ ["_evict_xformers_built_for_another_torch", "_evict_xformers_requiring_another_torch"]), step13assert "_install_torchao_for_torch" not in _calls_in(guards[0])@@ -292,14 +292,14 @@ class TestStepTotals:# Both carry the Windows-only accelerate repair (8c), which ignores NO_TORCH; the# no-torch case also gets the runtime-deps slot an update announces separately. Both also# carry the diffusers main slot (11c), which is spent on every path including opting out.- # With torch, the causal-conv1d + mamba-ssm slot (#13396) sits under flash-attn's gate.- assert _base_total(IS_WINDOWS = True) == 19+ # causal-conv1d and mamba-ssm have no slot: they install when a model needs them.+ assert _base_total(IS_WINDOWS = True) == 18assert _base_total(IS_WINDOWS = True, NO_TORCH = True) == 16@pytest.mark.parametrize("flags,total",[- ({}, 19), # Linux, torch (incl. the causal-conv1d + mamba-ssm slot)+ ({}, 18), # Linux, torch({"NO_TORCH": True}, 16), # Linux, GGUF-only (incl. the no-torch runtime step)# Two MLX slots (install + re-resolve) plus the grammar engine (11d).({"IS_MACOS": True, "IS_MAC_ARM": True}, 17), # Apple Silicon