Skip to content

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

Merged
danielhanchen merged 21 commits into
mainfrom
fix/inference-ssm-autoinstall
Jun 22, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
fix/inference-ssm-autoinstall

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

Loading a Mamba/SSM hybrid model for inference / chat in Studio fails with:

Failed to load model: mamba-ssm is required by the Mamba model but cannot be imported

These models (Nemotron-H / Nemotron-3-Nano, Falcon-H1, Granite-4.0-H, GraniteMoEHybrid, and linear-attention hybrids like Qwen3-Next / LFM2) lazily import mamba_ssm / causal_conv1d inside their modeling_*.py during from_pretrained. If those kernel packages are not installed, the load dies.

The training worker already handles this: core/training/worker.py calls _ensure_causal_conv1d_fast_path + _ensure_mamba_ssm (wheel-first) before a fine-tune, so the same model trains fine. The inference worker had no equivalent, so a model that trains out of the box could not be loaded for chat.

Fix

Add a shared, callback-based helper utils/ssm_runtime.py and call it from the inference worker's load path (core/inference/worker.py: _handle_load), right after the malware/consent gates and before from_pretrained. It mirrors the training worker:

  • ensure_ssm_runtime(model_name, status_cb=..., run=...) installs causal_conv1d (and mamba_ssm for true SSM hybrids), wheel-first via the same utils.wheel_utils primitives the training worker uses, then a PyPI source build as fallback.
  • No-op and idempotent for non-SSM models and when the kernels are already present.
  • On failure it surfaces a clear "this model needs SSM kernels that could not be installed" load error instead of the cryptic mid-load import mamba_ssm crash.

Detection (model_is_ssm, model_wants_causal_conv1d) and the pinned wheel versions mirror the training worker so the same set of models is covered on both surfaces.

Scope / safety

  • The training worker is not modified (zero risk to the fine-tune path).
  • The two copies of the SSM detection + pinned versions are kept in lockstep by a drift-guard test (test_constants_match_training_worker) that fails if they diverge.
  • For non-SSM models the load path is unchanged (the helper returns immediately).

Tests

tests/test_ssm_runtime.py (23 tests):

  • detection for SSM, causal-conv1d-only, and plain models;
  • ensure_ssm_runtime installs causal-conv1d then mamba-ssm in order, skips mamba for causal-only models, no-ops for non-SSM, and raises on install failure;
  • _install_kernel is idempotent when present, uses the prebuilt wheel when available, and falls back to a source build otherwise (all mocked, no network);
  • inference worker wiring is present;
  • drift guard: detection + pinned versions match the training worker.

Existing inference/security/consent suites stay green. (The pre-existing failures in tests/test_training_worker_flash_attn.py are unrelated to this change and reproduce identically on main.)

danielhanchen and others added 2 commits June 21, 2026 08:50
Mamba/SSM hybrids (Nemotron-H/Nano, Falcon-H1, Granite-4.0-H, ...) lazily import
mamba_ssm / causal_conv1d during from_pretrained, so loading them for chat failed
with 'mamba-ssm is required by the Mamba model but cannot be imported'. The training
worker already wheel-first installs these before a fine-tune; the inference worker
did not. Add utils/ssm_runtime.ensure_ssm_runtime and call it from the inference load
path so the same models load for inference. Training worker is untouched; a drift
test keeps the shared detection and pinned versions in lockstep.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces an automatic runtime installation mechanism for SSM/Mamba kernels (causal_conv1d and mamba_ssm) in the inference worker, ensuring hybrid models load successfully for chat just as they do during training. It adds the ssm_runtime utility module and a comprehensive test suite. The review feedback highlights a critical issue where dynamically installed packages may fail to import within the running Python process because the import system caches are not invalidated. It is recommended to call importlib.invalidate_caches() after installations and within the import check, while also catching the more specific ModuleNotFoundError to avoid suppressing unrelated import errors.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +97 to +102
__import__(import_name)
return True
except ImportError:
return False


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

When packages are dynamically installed at runtime (via pip or uv) within a running Python process, Python's import system finder caches (such as sys.path_importer_cache) must be invalidated using importlib.invalidate_caches(). Without this, subsequent imports of the newly installed packages (like causal_conv1d or mamba_ssm) can fail with ModuleNotFoundError or ImportError because the import machinery is unaware of the new files in site-packages.

Calling importlib.invalidate_caches() inside _is_importable ensures that any recent installation is correctly detected. Additionally, when catching an import error for an optional dependency, prefer catching the more specific ModuleNotFoundError and check the module name to avoid suppressing unrelated import errors.

Suggested change
__import__(import_name)
return True
except ImportError:
return False
def _is_importable(import_name: str) -> bool:
import importlib
importlib.invalidate_caches()
try:
__import__(import_name)
return True
except ModuleNotFoundError as e:
if e.name == import_name:
return False
raise
References
  1. When catching an ImportError for an optional dependency, prefer catching the more specific ModuleNotFoundError and check the module name to avoid suppressing unrelated import errors.

Comment thread studio/backend/utils/ssm_runtime.py Outdated
Comment on lines +155 to +157
return True
logger.warning(
"%s could not install %s wheel:\n%s",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

After a successful wheel installation, we should invalidate the import caches immediately to ensure that subsequent imports of the newly installed package in the same process do not fail with ModuleNotFoundError.

            if getattr(result, "returncode", 1) == 0:
                logger.info("Installed prebuilt %s wheel", display_name)
                import importlib
                importlib.invalidate_caches()
                return True

Comment on lines +190 to +194
"-m",
"pip",
"install",
"--no-build-isolation",
"--no-deps",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

After a source build installation, we should invalidate the import caches before checking if the package is importable to ensure that the check succeeds and subsequent imports work correctly.

Suggested change
"-m",
"pip",
"install",
"--no-build-isolation",
"--no-deps",
if getattr(result, "returncode", 1) != 0:
logger.warning(
"%s source install failed:\n%s", display_name, getattr(result, "stdout", "")
)
import importlib
importlib.invalidate_caches()
return _is_importable(import_name)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f47d4abec5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +244 to +245
ensure_ssm_runtime(
config["model_name"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Skip SSM kernel installs on the MLX load path

In the MLX fast-path this same _handle_load is called with an MLXInferenceBackend, so this unconditional pre-load install runs for Apple Silicon too. For model ids matching qwen3-next, qwen3.5, lfm2, or Nemotron/Falcon/Granite hybrids, ensure_ssm_runtime tries to install causal-conv1d/mamba-ssm even though MLX does not use these CUDA/Torch kernels; on macOS there is no compatible prebuilt wheel and the source build can fail before MLXInferenceBackend.load_model is ever reached, causing ssm_runtime_install_failed for models that should load through MLX. Gate this by backend/device or skip the helper for the MLX path.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +244 to +245
ensure_ssm_runtime(
config["model_name"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include LoRA base model in SSM runtime detection

For LoRA loads, ModelConfig.from_identifier resolves mc.base_model and FastLanguageModel.from_pretrained(config.path) loads the adapter's base, but this call checks only the adapter repo/path. If an adapter named like someone/my-chat-lora points at an SSM base such as nvidia/Nemotron-H-*, the substring detectors return false, no kernels are installed, and the later from_pretrained hits the same missing mamba_ssm/causal_conv1d import this change is meant to prevent. Run the helper over the resolved base model as well when mc.is_lora.

Useful? React with 👍 / 👎.

Comment thread studio/backend/utils/ssm_runtime.py Outdated
sys.executable, "-m", "pip", "install",
"--no-build-isolation", "--no-deps", "--no-cache-dir", spec,
]
result = run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep source builds from tripping the load inactivity timeout

When no prebuilt wheel exists, the fallback build runs synchronously after emitting only one status message, while the inference orchestrator's _wait_response uses a 300s inactivity timeout that is reset only by further status events. For source builds that take more than five minutes, the parent can time out and kill the worker even though pip is still compiling. Start the load heartbeat before this install or emit periodic progress/status while the build is running.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +244 to +245
ensure_ssm_runtime(
config["model_name"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Install SSM kernels before importing Transformers

At this point the worker has already imported core.inference.inference, whose module top level imports unsloth and transformers. In a fresh environment where these kernels were absent at import time, Transformers' optional-dependency availability flags can already be cached as false, so installing causal-conv1d/mamba-ssm here may still leave model code that checks those helpers on the missing-dependency path for Qwen3-Next/Nemotron-style loads. Move this ensure step before the ML library import phase or refresh the relevant Transformers availability state after installation.

Useful? React with 👍 / 👎.

Comment thread studio/backend/utils/ssm_runtime.py Outdated
sys.executable, "-m", "pip", "install",
"--no-build-isolation", "--no-deps", "--no-cache-dir", spec,
]
result = run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve ROCm HIP source-build setup

For ROCm users with no compatible prebuilt wheel, this fallback now invokes the source build without the HIP handling that the training worker relies on: checking for hipcc, adding --no-cache, using a longer HIP timeout, and injecting HIPCC_COMPILE_FLAGS_APPEND=--gcc-install-dir=... for Ubuntu 24.04/ROCm clang. In that environment the inference load can fail compiling causal-conv1d/mamba-ssm even though the same model trains successfully through the existing HIP-aware installer path. Mirror the training worker's HIP branch here before running pip.

Useful? React with 👍 / 👎.

- Invalidate importlib finder caches in _is_importable and after a successful
  wheel install, so a kernel installed earlier in this same process is actually
  importable when the modeling code lazy-imports it during from_pretrained.
- Skip the SSM kernel install entirely on the MLX (Apple Silicon) load path:
  these are CUDA/ROCm Torch kernels with no MLX use and no macOS prebuilt wheel,
  so the source build would fail before the MLX backend loads the model.
- For LoRA loads, also run detection over the resolved base model, since an
  adapter id like 'me/my-lora' won't match the SSM heuristics but its SSM base
  (Nemotron-H, ...) is what needs the kernels.

Adds tests for cache invalidation and the MLX-skip / LoRA-base worker wiring.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d23d725a5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/utils/ssm_runtime.py Outdated
"--no-cache-dir",
spec,
]
result = run(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, text = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mirror the ROCm source-build setup

When probe_torch_wheel_env() reports ROCm, direct_wheel_url() returns no wheel because it only builds CUDA URLs, so ROCm users always reach this source-build command. This new path omits the training worker's HIP branch that checks for hipcc and sets HIPCC_COMPILE_FLAGS_APPEND with a usable gcc install dir; on the Ubuntu 24.04/ROCm clang layout covered by the existing training tests, these kernels fail to compile, so chat loading returns ssm_runtime_install_failed for models that fine-tuning can prepare.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
if mc.is_lora and getattr(mc, "base_model", None):
ssm_targets.append(str(mc.base_model))
for ssm_target in dict.fromkeys(ssm_targets):
ensure_ssm_runtime(ssm_target, status_cb = _ssm_status)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Start the heartbeat before SSM source builds

When there is no prebuilt SSM wheel, ensure_ssm_runtime() drops into a blocking pip source build and only sends the one status message before the build starts. This call currently runs before start_watchdog, while core/inference/orchestrator.py:_wait_response() times out after 300s of no status, so a build taking more than five minutes is reported as a failed load even if the install later succeeds. Start the watchdog before this install or emit periodic status while the subprocess build is running.

Useful? React with 👍 / 👎.

Comment thread studio/backend/utils/ssm_runtime.py Outdated
# Make the just-written wheel importable in this process.
importlib.invalidate_caches()
logger.info("Installed prebuilt %s wheel", display_name)
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Verify prebuilt wheels before proceeding

When pip/uv returns success but the installed extension still cannot import (for example a mismatched CUDA/CXX ABI wheel or missing shared library), this returns success without checking _is_importable(). That skips the new ssm_runtime_install_failed path and lets from_pretrained fail later with the same cryptic lazy-import error this change is meant to avoid; the source-build path already verifies importability, so the wheel path should do the same before returning.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

…tbeat

Address review feedback:
- Verify a prebuilt wheel actually imports before trusting it; a CUDA/ABI-mismatched
  wheel now falls back to a source build instead of returning success and failing later
  with the cryptic lazy-import error.
- HIP-aware source build: require hipcc on ROCm, inject clang --gcc-install-dir, and use
  the 1800s timeout, mirroring the training worker (ROCm has no prebuilt wheel).
- Emit a status heartbeat every 60s during the source build so a long (ROCm) build does
  not trip the orchestrator's 300s inactivity timeout.

Tests cover the wheel-not-importable fallback and the missing-hipcc ROCm bail.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fa929e073c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/utils/ssm_runtime.py Outdated
Comment on lines +303 to +305
raise RuntimeError(
"Could not install causal-conv1d, required by this model's Mamba layers."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep causal-conv1d-only installs best-effort

When model_wants_causal_conv1d matches but model_is_ssm is false (for example Qwen3-Next/LFM2), this raise turns a missing or failed causal-conv1d fast-path install into a hard load failure. Those models can fall back to torch implementations when the kernel is unavailable, and the training path this mirrors treats the same install as best-effort (_ensure_causal_conv1d_fast_path ignores the install result and skips Windows). On Windows, CPU, non-MLX macOS, or CUDA/Python combinations without a matching wheel/compiler, Studio will now reject otherwise loadable chat models before from_pretrained; only make the load fatal for true SSM/mamba requirements or continue after a causal-conv1d failure.

Useful? React with 👍 / 👎.

Comment thread studio/backend/utils/ssm_runtime.py Outdated
Comment on lines +229 to +231
"--no-build-isolation",
"--no-deps",
spec,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add --no-cache for ROCm uv source builds

When this source-build path runs on ROCm with uv available, it omits the --no-cache flag that the training worker adds specifically to avoid reusing stale artifacts from partial HIP builds; uv --help confirms --no-cache avoids reading from or writing to the cache. In that environment, a previously interrupted or failed causal-conv1d/mamba-ssm HIP build can keep poisoning inference retries even though the equivalent training install path bypasses the cache, so mirror the training command when is_hip is true.

Useful? React with 👍 / 👎.

Comment on lines +195 to +197
"%s wheel installed but not importable; building from source", display_name
)
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Force rebuild when the installed wheel fails to import

In the path where a wheel command returns 0 but _is_importable is still false, the package is already installed at the exact pinned version, so the following uv pip install ... <name>==<version> / pip install ... <name>==<version> source step can no-op as already satisfied instead of rebuilding; pip install --help says --force-reinstall is what reinstalls already up-to-date packages, and uv pip install --help exposes the analogous --reinstall. For a CUDA/ABI-mismatched wheel this means the intended source fallback does not actually replace the broken install, so the SSM load still fails.

Useful? React with 👍 / 👎.

- causal-conv1d is a fast path: models that merely want it (Qwen3-Next, LFM2)
  fall back to torch, so a failed install must not reject an otherwise loadable
  chat model on Windows/CPU/macOS or an ABI without a wheel. Only a true SSM
  model's mamba-ssm requirement stays fatal, matching the training worker which
  treats causal-conv1d as best-effort.
- The source build is reached only when not importable, including a wheel that
  installed but failed to import; add --reinstall/--force-reinstall so it
  replaces the broken install instead of no-opping as already satisfied.
- Add --no-cache to the ROCm uv source build to avoid reusing stale artifacts
  from a partial HIP build, mirroring the training worker.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8531a1b2f6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +302 to +311
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,
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip causal-conv1d source builds on Windows

On Windows loads of causal-conv1d-only models such as Qwen3-Next or LFM2, this best-effort call enters _install_kernel; since linux_wheel_platform_tag() returns None off Linux, it bypasses the wheel path and runs a source pip install causal-conv1d==1.6.1 before falling back. The training worker explicitly skips the causal-conv1d fast path on Windows, so chat loads can spend time failing an unsupported native build on every load for models that should still use their torch fallback. Please add the same platform guard before invoking the causal-conv1d install.

Useful? React with 👍 / 👎.

Comment on lines +102 to +106
try:
__import__(import_name)
return True
except ImportError:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat broken native imports as unavailable

When a stale or ABI-mismatched native kernel package is installed, importing it can raise an import-time OSError or RuntimeError rather than ImportError; this probe then propagates out of _install_kernel instead of returning False. In the inference load path that becomes ssm_runtime_install_failed, so even causal-conv1d-only models with a torch fallback can be rejected and the intended wheel/source fallback is not attempted. Please catch non-fatal import exceptions from these optional native packages and treat the kernel as unavailable.

Useful? React with 👍 / 👎.

Comment on lines +168 to +170
if _is_importable(import_name):
logger.info("%s already installed", display_name)
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reinstall stale SSM kernels before loading

In environments that already have an older but importable mamba-ssm or causal-conv1d, this short-circuits before comparing the installed distribution to the pinned versions above, then proceeds to from_pretrained with that stale runtime. These kernels expose version-specific APIs/compiled extensions, so a previous install can still fail during the SSM model load even though the auto-install path reported it as satisfied. Please verify the installed package version and reinstall when it is below the pinned runtime.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8531a1b2f6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/utils/ssm_runtime.py Outdated
try:
__import__(import_name)
return True
except ImportError:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle broken native kernels as not importable

When a previously installed native kernel is ABI-incompatible with the current torch/CUDA stack (for example after a torch upgrade), importing causal_conv1d or mamba_ssm commonly raises OSError/RuntimeError such as an undefined symbol rather than ImportError. Because _is_importable() lets those exceptions escape, the new pre-load path reports ssm_runtime_install_failed instead of treating the package as broken and falling back to reinstall/source build; this also turns the documented best-effort causal-conv1d path for Qwen3-Next/LFM2 into a hard load failure in that environment.

Useful? React with 👍 / 👎.

# causal-conv1d first: SSM modeling files lazy-import it during from_pretrained, and
# mamba-ssm's fast path uses it. Best-effort (mirrors training): on a platform/ABI
# without a wheel or compiler the model still loads on its torch fallback.
if wants_causal_conv1d and not _install_kernel(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip Windows causal-conv1d source builds

On Windows, loading a causal-conv1d-only model such as Qwen3-Next/LFM2 now enters _install_kernel even though the training path explicitly skips causal-conv1d on sys.platform == "win32" because there is no prebuilt wheel. Since the new source-build path has no non-HIP timeout, chat loads can spend minutes or hang compiling an optional package before continuing on the torch fallback, which is a regression for models that do not require this kernel to load.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
if mc.is_lora and getattr(mc, "base_model", None):
ssm_targets.append(str(mc.base_model))
for ssm_target in dict.fromkeys(ssm_targets):
ensure_ssm_runtime(ssm_target, status_cb = _ssm_status)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Install SSM kernels before importing transformers

In the normal inference subprocess, run_inference_process imports core.inference.inference before _handle_load, and that module imports unsloth/transformers; transformers records optional-backend availability during import. In a fresh environment without mamba_ssm/causal_conv1d, installing them here leaves those already-imported availability flags false, so Nemotron/Falcon/Granite-style loads can still fail at from_pretrained with the same “mamba-ssm is required” error this change is meant to avoid. Move this install before the inference backend/transformers import or refresh/rebind the transformers import-utils gates after installation.

Useful? React with 👍 / 👎.

…t + Windows

Codex:
- Install the SSM kernels before importing transformers. run_inference_process
  imported core.inference.inference (which imports unsloth/transformers) before the
  load, and a sidecar transformers can evaluate its optional-backend gates against
  the import state; installing causal_conv1d/mamba_ssm afterwards left those gates
  unsatisfied and a Nemotron/Falcon/Granite load still failed with "mamba-ssm is
  required". The initial model's kernels are now installed in run_inference_process
  before the ML import, via a shared _ensure_ssm_kernels helper; _handle_load keeps
  calling it (idempotent) for a LoRA's base and for later in-process loads.
- _is_importable now treats any import failure as "not importable", not only
  ImportError. An ABI-incompatible native kernel (undefined symbol after a torch/CUDA
  upgrade) raises OSError/RuntimeError; letting those escape reported
  ssm_runtime_install_failed instead of falling back to reinstall/source build.
- Skip causal-conv1d on Windows (no prebuilt wheel), mirroring the training worker.
  A causal-conv1d-only model (Qwen3-Next/LFM2) no longer drops a chat load into a
  multi-minute untimed source build; it uses the torch fallback. mamba-ssm is still
  attempted for true SSM hybrids.

Tests: test_ssm_runtime.py +5 (broken-kernel exceptions read as not-importable;
causal-conv1d skipped on win32 while mamba-ssm still installs). 36 passed.
@danielhanchen

Copy link
Copy Markdown
Member Author

Addressed the review:

  • Install the SSM kernels before transformers is imported. run_inference_process imported core.inference.inference (which imports unsloth/transformers) before the load, and a sidecar transformers can snapshot its optional-backend gates at import; installing causal_conv1d/mamba_ssm afterwards left the gate unsatisfied so the load still failed with "mamba-ssm is required". The initial model's kernels are now installed in run_inference_process before the ML import via a shared _ensure_ssm_kernels helper; _handle_load keeps calling it (idempotent) for a LoRA's base and later in-process loads.
  • _is_importable now treats any import failure as not-importable, not only ImportError. An ABI-incompatible kernel (undefined symbol after a torch/CUDA upgrade) raises OSError/RuntimeError; letting those escape reported ssm_runtime_install_failed instead of falling back to reinstall/source build.
  • Skip causal-conv1d on Windows (no prebuilt wheel), mirroring the training worker, so a causal-conv1d-only model (Qwen3-Next/LFM2) no longer drops a chat load into a multi-minute source build; mamba-ssm is still attempted for true SSM hybrids.

Tests: 36 passed (+5).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b03ad1501d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +278 to +282
if getattr(backend, "device", None) != "mlx":
ssm_targets = [config["model_name"]]
if mc.is_lora and getattr(mc, "base_model", None):
ssm_targets.append(str(mc.base_model))
if not _ensure_ssm_kernels(ssm_targets, resp_queue):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not install SSM kernels after transformers is imported

When the SSM target is only known in _handle_load (for example after first loading a plain model and then sending a load command for a Mamba/SSM model, or for a remote LoRA whose base is resolved by ModelConfig), this block runs after run_inference_process has already imported core.inference.inference/transformers. The nearby pre-import path notes that transformers caches optional-backend availability at import time, so installing mamba_ssm here can still leave from_pretrained seeing the backend as unavailable and fail with the original mamba-ssm is required error; these cases need a pre-transformers install or a worker restart before loading.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +768 to +772
_ssm_base = _resolve_base_model(model_name)
_ssm_targets = [model_name]
if _ssm_base and _ssm_base != model_name:
_ssm_targets.append(_ssm_base)
if not _ensure_ssm_kernels(_ssm_targets, resp_queue):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run security gates before installing kernels

For an initial load, this pre-transformers install runs before _handle_load builds/validates ModelConfig and before its malware/remote-code consent gates. Any user-supplied identifier that merely contains one of the SSM substrings (including a nonexistent repo or one the gates would later block) will download/install or even source-build native packages before the load is rejected, mutating the environment and spending minutes of work for a model that should never proceed.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7d8e807561

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +783 to +786
_ssm_base = _resolve_base_model(model_name)
_ssm_targets = [model_name]
if _ssm_base and _ssm_base != model_name:
_ssm_targets.append(_ssm_base)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve remote LoRA bases before importing transformers

When the initial model is a remote HF LoRA adapter whose repo name does not itself contain an SSM substring but whose adapter_config.json points at a Nemotron/Falcon/Granite base, this pre-import target list misses the base: _resolve_base_model() only resolves local files/directories, while the remote base is not discovered until ModelConfig.from_identifier() runs in _handle_load. At that point transformers has already been imported and its optional-backend availability has been snapshotted, so installing mamba-ssm/causal-conv1d there is too late and the load can still fail with the missing-kernel error this change is meant to avoid.

Useful? React with 👍 / 👎.

_resolve_base_model only reads a local adapter_config.json, so a remote LoRA
adapter whose own id has no SSM substring but whose base is a Nemotron/Falcon/
Granite model had its base discovered only by ModelConfig in _handle_load, after
transformers was imported and its optional-backend availability snapshotted, so
the SSM kernel install there was too late. Add _remote_lora_base, a metadata-only
adapter_config.json fetch (no huggingface_hub / transformers import), and use it
in the pre-import path so the base is gated and its kernels pre-installed.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1bd0c1f122

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +797 to +798
if not _run_security_gates(
_ssm_targets,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Limit pre-import security gates to actual load roots

When the initial model is a local full fine-tuned checkpoint, _resolve_base_model() can return model_name/_name_or_path from config.json even though the load does not fetch that remote base (the authoritative _handle_load gate only adds mc.base_model for mc.is_lora). Passing _ssm_targets here therefore scans and can block the remote base before the local checkpoint loads; e.g., a safe local full checkpoint whose recorded base repo has a Hub malware or remote-code finding is refused despite no base weights/code being loaded. Keep the SSM-install target list separate from the security target list, or only add the resolved base to the gate for confirmed LoRA adapters.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +788 to +790
_remote_base = _remote_lora_base(model_name, hf_token = _hf_token)
if _remote_base:
_ssm_base = _remote_base

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve remote LoRA base before choosing transformers

For a remote LoRA whose adapter repo name does not include the base architecture, _activate_transformers_version(model_name) has already selected the transformers tier before this adapter_config.json lookup discovers the base. If the base is one of the newly handled causal/SSM families that also requires a sidecar transformers version (for example a generic adapter on Qwen/Qwen3-Next-*), the kernels are preinstalled but the worker still imports the default transformers package and the load fails. Resolve the remote base before activation, or pass the resolved base into the version selection path.

Useful? React with 👍 / 👎.

Comment on lines +284 to +286
or _env_offline()
):
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Read cached remote LoRA bases while offline

When HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE is set, this returns None before checking the local Hugging Face cache, but cached remote adapters are still loadable through the existing ModelConfig path. For an offline cached LoRA whose base is an SSM model and whose adapter name does not itself match the SSM substrings, the base is only discovered later in _handle_load, after transformers has already been imported, so the required kernels are installed too late and the load still fails. Check cached adapter_config.json before bailing out for offline mode.

Useful? React with 👍 / 👎.

…cache

Three follow-ups to the pre-import resolution:

- The security gate reused the SSM target list, which for a local full fine-tune
  includes the config.json-recorded base. That base is never loaded, so scanning
  it could falsely block a safe local checkpoint. Gate only the model plus a
  genuine LoRA base (matching _handle_load's mc.is_lora), separate from the
  broader SSM-install list.

- Tier activation ran on the raw adapter id, so a remote LoRA whose base needs a
  sidecar transformers version imported the default and failed. Resolve the base
  once up front and activate on it.

- _remote_lora_base bailed on offline before checking the hub cache, missing a
  cached adapter's base. Read the cached adapter_config.json when offline or when
  the fetch fails.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: edca8add7e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +275 to +278
model_name
and model_name.count("/") == 1
and model_name[0] not in "/.~"
and "\\" not in model_name

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid treating relative local paths as Hub repos

When model_name is an existing relative local path with exactly one slash (for example outputs/run1), this predicate still returns true even though the repo's utils.paths.is_local_path() treats existing relative paths as local. _remote_lora_base() then performs a Hugging Face raw request/cache lookup before _resolve_base_model(), which can add a 10s delay to local checkpoint loads and can activate/gate/install against an unrelated remote adapter base if a same-named Hub repo/cache entry exists. Reuse is_local_path() or check Path(...).exists() before accepting the owner/repo shape.

Useful? React with 👍 / 👎.

Comment on lines +351 to +353
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat a missing adapter config as not a LoRA

When the raw adapter_config.json request gets a definitive 404 for a repo that is now a full model or otherwise not a LoRA, this broad fallback can still return an old cached adapter base for the same repo. In that scenario the worker activates Transformers and runs security/SSM setup for the stale base before loading the current repo; if the current model needs a different Transformers tier, the subprocess imports the wrong version and the load can fail. Distinguish HTTPError 404 from transient/offline failures and only consult the cache for the latter.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
Comment on lines +216 to +217
_fs = evaluate_file_security(
target, hf_token = hf_token, load_subdirs = security_load_subdirs(target, hf_token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep pre-import security checks from importing Transformers

For an initial SSM load where the kernels are not already installed, this security_load_subdirs() call runs before _ensure_ssm_kernels(), but the helper imports utils.models.model_config, whose module initialization imports transformers.models.auto. That means Transformers snapshots optional backend availability before causal-conv1d/mamba-ssm are installed, so the later install can still be invisible and the SSM from_pretrained path fails with the same missing-backend error this change is meant to prevent. Make this pre-install gate avoid model_config/Transformers imports, or install kernels before any path that can import Transformers.

Useful? React with 👍 / 👎.

…tion

The pre-import security gate called security_load_subdirs, which imports
model_config and thus transformers, snapshotting optional-backend availability
before the SSM kernels are installed and defeating the ordering. Add
compute_subdirs to _run_security_gates and pass False in the preflight so it scans
from the root only (transformers-free); _handle_load still runs the authoritative
gate with full subdir scoping after the import.

_remote_lora_base now skips existing local relative paths (is_local_path) so a
checkpoint like outputs/run1 is never treated as a Hub repo, and distinguishes a
definitive 404 (not a LoRA -> None) from transient/offline failures (read the
cache), so a repo that is now a full model no longer resolves a stale cached base.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bfe7087b39

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +76 to +77
name = (model_name or "").lower()
return any(sub in name for sub in SSM_MODEL_SUBSTRINGS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard local paths before SSM substring matches

When model_name is a local checkpoint path, this matches the SSM substrings against the entire directory path, including arbitrary parent folder names. For example, a normal Llama checkpoint under /models/falcon-h1-experiment/llama-checkpoint is classified as a true SSM model, causing ensure_ssm_runtime to require mamba-ssm and fail the load if that native package cannot be installed even though the model does not need it. The transformer tier detector already short-circuits local config.json before name heuristics; this path needs the same guard or should match only actual repo/model identifiers.

Useful? React with 👍 / 👎.

import urllib.error
import urllib.request

url = f"https://huggingface.co/{model_name}/raw/main/adapter_config.json"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Respect Hub revision/endpoint for adapter configs

For a remote LoRA whose SSM base is only discoverable from adapter_config.json, this pre-import lookup is the only chance to install mamba-ssm before transformers snapshots optional-backend availability. Hardcoding huggingface.co/.../raw/main ignores HF_ENDPOINT/Enterprise mirrors and repos whose default branch is not main; ModelConfig can still resolve the adapter later via hf_hub_download, but that happens after the transformers import, so _handle_load installs the kernels too late and the load can still fail. This lookup should use the Hub client's endpoint/default-revision handling without importing transformers.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/inference/worker.py Outdated
):
return
# SSM install also covers a full fine-tune's base name (reveals the SSM architecture).
_ssm_targets = [model_name]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip adapter names when probing LoRA SSM kernels

When _lora_base is set, the architecture code that can require mamba-ssm comes from the base model, while the adapter repo name is arbitrary. Starting _ssm_targets with the adapter id means a normal Llama LoRA named like user/falcon-h1-lora is treated as a true SSM model and the load is blocked if mamba-ssm cannot be installed, even though the resolved base does not need it. For LoRA loads, probe the base model for SSM kernels instead of the adapter identifier.

Useful? React with 👍 / 👎.

model_is_ssm is a substring match, so an arbitrary name could false-match and
force a mamba-ssm install that fails the load for a non-SSM model:
- a LoRA adapter id like user/falcon-h1-lora (the SSM-relevant code is the base's);
- a local checkpoint under an SSM-named parent dir, e.g. /runs/falcon-h1/llama-ckpt.

Add ssm_probe_identifier, which resolves the base (or a bare local checkpoint's
basename) and feed that to ensure_ssm_runtime from both the pre-import path and
_handle_load, so detection runs against a real model id, never an adapter id or
parent folders.

_remote_lora_base now honors HF_ENDPOINT so enterprise/mirror deployments resolve
the adapter base instead of always hitting huggingface.co.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 0e24841c49

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen
danielhanchen merged commit 2a05426 into main Jun 22, 2026
31 of 38 checks passed
@danielhanchen
danielhanchen deleted the fix/inference-ssm-autoinstall branch June 22, 2026 11:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants