Repository navigation
Studio: restore Qwen causal-conv1d on demand, narrow fatal mamba-ssm, provision SSM kernels in export - #13971
Conversation
…rovision SSM kernels in export - Request causal-conv1d on demand again for Qwen3.5/3.6/Qwen3-Next in training, inference and Clef - mamba-ssm stays required only for nemotron_h, falcon_h1 and granitemoehybrid; newer SSM families continue on the torch path - Resolve local adapter bases and the adapter base pin before deciding kernels - Export worker provisions SSM kernels before importing Unsloth - Inference re-reads modeling sources without importing transformers and respawns the worker once after a fresh install - Setup removes causal-conv1d / mamba-ssm builds that no longer import after a torch change - Skip flash-attn downloads below sm80 at setup and for long-context training
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
- Stale kernel removal needs proof: torch imports, then the extension import completes with an ImportError / OSError; a broken torch, a signal, a hang or an unrelated exit keeps the kernel - unsloth install-kernels --without-gpu (or UNSLOTH_INSTALL_KERNELS_WITHOUT_GPU=1) provisions GPU-gated kernels in a GPU-less image build; skipped kernels are listed, and a named kernel that was skipped exits non-zero - Inference respawn never spawns over a worker that survived shutdown - SSM restart and Xet fallback each get their own one-use retry, at most three spawns, with an accurate stall message - Restart only for imported modeling modules, including the selected remote-code model's - Export skips SSM provisioning on macOS, MLX and CPU - UV_OFFLINE counts as offline for on-demand kernel installs - Long-context flash-attn: no probe when already importable, reuse the worker's torch, never apply the sm80 floor on ROCm
… matching - install-kernels checks an already-working extension before the wheel, GPU and offline skips (a ROCm source build or a GPU-hidden builder's install is success); skipped kernels are listed and exit 0 as before, --strict opts into exit 2 - install-kernels installs nothing offline (UV_OFFLINE, HF_HUB_OFFLINE, TRANSFORMERS_OFFLINE), and install_wheel never falls back from an offline uv to pip - Restart detection takes the implementation modules from the config's auto_map (any module name) and matches transformers_modules.<checkpoint namespace> exactly, both spellings - Export decides the CPU / MLX / macOS bypass before the connectivity window
… up, lock - A wheel whose HEAD check is unanswered is still downloaded and verified (as setup did); only a real download / import failure falls back, in inference, export and training - A failed install is not retried in the same process (keyed by kernel, torch and toolchain), so a load's preflight and _handle_load share one attempt; configs are read once per process - Optional mamba-ssm families (mamba, mamba2, falcon_mamba, jamba, zamba, zamba2, bamba) get a prebuilt wheel only, never a source build, and are skipped below setup's sm80 / sm75 + Triton 3.4 floor; Nemotron-H, Falcon-H1 and Granite-4.0-H keep the source fallback and no floor - CUDA source builds get the 1800 s deadline ROCm had, and a timeout stops the whole build tree - A failed runtime install removes the distribution whose extension does not import - One cross-process lock per kernel and environment covers precheck, install, verify and cleanup, rechecks after acquiring, reports while waiting and gives up after a bound - Only a CUDA or ROCm torch provisions kernels; export provisions only for a CUDA / ROCm backend
…source builds - The Unsloth prebuilt resolver answers only for (platform, torch, interpreter) cells the release carries: torch 2.13 / 2.14 are cp313 on every platform, so linux_x86_64 cp310-cp312 and win_arm64 cp311 / cp312 no longer get a URL that 404s; no upstream URL for torch 2.13+ either - No source build of the pinned causal-conv1d 1.6.1 / mamba-ssm 2.3.1 on torch 2.13+ (C++17 sources against C++20 torch headers): the prebuilt wheel or the torch path, in inference, export and training - Training stops with the inference error when Nemotron-H, Falcon-H1 or Granite-4.0-H cannot get mamba-ssm on a CUDA / ROCm torch, including Windows without triton-windows - The MLX training-worker test stubs the wheel_utils names the worker now imports
The pinned upstream releases (causal-conv1d v1.6.1.post4, mamba-ssm v2.3.1) publish CUDA 11 / 12 / 13 Linux wheels for a fixed set of torch minors and cp310-cp313 only; CUDA 13 before torch 2.9, aarch64 before 2.7 and abiFALSE after 2.6 were URLs that 404 in front of the source fallback. The cells are now a table read from the two asset lists, and a test ties every URL the resolver can emit to it.
Nemotron-H, Falcon-H1 and Granite-4.0-H keep the source fallback, but a failed install or a Windows torch without triton-windows no longer stops the run: their native transformers path can run without mamba-ssm, so training reports it and continues, as it did before.
Nemotron-H, Falcon-H1 and Granite-4.0-H still try mamba-ssm first (source build included), but a failed install now refuses the chat or export load only when that load imports code that cannot run without it: remote modeling code (auto_map, under trust_remote_code or with no native class) that imports mamba_ssm unconditionally, or a model type the installed transformers has no native implementation of. Their native transformers models run without it, so otherwise the load goes ahead on the torch path with a warning, as before #13861 (a Nemotron-H checkpoint on Windows ROCm was refused).
…nel builds - Training's eager causal-conv1d install and its fast-path hook share the runtime's failed-attempt memo (same key), so a failed CUDA / HIP build is never repeated in one worker - Only successful config reads are cached; a miss is read again next time - A kernel a peer installed while this worker waited counts as new here, so inference refreshes or restarts its already-imported modeling modules - The install lock lives beside the environment (else one per environment in the temp folder), and every mutating entry point takes it: Studio workers, setup's stale-kernel removal and unsloth install-kernels. A lock that cannot be opened or taken skips the install instead of racing unguarded; optional accelerations wait at most 120 s for a peer, required ones 2400 s - Force-terminating a training run first stops the processes its worker started, including a source build in its own session - A runtime install whose installer cannot even start still removes a broken copy and is remembered as failed - Tests never take the environment's real install locks
…amba / Zamba / Bamba _ensure_mamba_ssm defaulted essential to True, so a caller that left it out (the ROCm hardware probe on gfx1151) compiled mamba-ssm from source for a Mamba2 model for 60 s. Unspecified now means the name decides: only Nemotron-H, Falcon-H1 and Granite-4.0-H may build it.
|
The The new skip message in |
|
@codex review |
|
@codex security review |
|
@codex review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 75fdaa259b
ℹ️ 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".
| if not _provision_ssm_kernels( | ||
| checkpoint_path, | ||
| config.get("base_model") or None, |
There was a problem hiding this comment.
Run export security gates before provisioning kernels
For a checkpoint that the malware or remote-code consent gate rejects, this startup path installs or even source-builds native SSM packages before _handle_load reaches those gates at all. A blocked model can therefore modify the shared Python environment and consume up to the source-build timeout before the export is refused; perform a transformers-free security preflight, as the inference worker does, before calling _provision_ssm_kernels.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7c90c5b: the malware and remote code consent gates now run before any kernel provisioning, so a rejected checkpoint never triggers an install or source build.
| try: | ||
| removed = _uninstall_distribution(distribution) |
There was a problem hiding this comment.
Re-probe the extension after acquiring the install lock
When another process is currently replacing the same kernel, the unlocked probe can observe its transient broken state and then wait for kernel_install_lock; after the peer finishes and releases the lock, this code immediately uninstalls the newly verified package using the stale probe result. Re-run the extension probe while holding the lock before removing the distribution.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7c90c5b: the extension is probed again after the install lock is acquired, so a concurrent replacement in progress is not mistaken for a broken install.
| "import torch\n" | ||
| "try:\n" | ||
| " import {extension}\n" | ||
| "except (ImportError, OSError) as exc:\n" |
There was a problem hiding this comment.
Treat RuntimeError from extension imports as stale
After a torch/CUDA upgrade, an ABI-incompatible PyTorch extension can raise RuntimeError as well as ImportError or OSError (the runtime installer already treats any of these failures as non-importable). In that case this child exits with an unrelated code, _remove_stale_ssm_kernels keeps the broken distribution, and later model loading can select its metadata and fail instead of reinstalling it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The stale check imports only the compiled extension module, where a torch ABI mismatch surfaces as ImportError (undefined symbol) and pybind init failures also become ImportError. Anything else is treated as inconclusive on purpose, because this setup time cleanup only removes a kernel on proof. A copy kept here is not left broken: at load, ssm_runtime treats any exception from the import as not importable and reinstalls the wheel, or removes the rejected copy before rebuilding. So the model load does not fail on it.
| if not _provision_ssm_kernels( | ||
| checkpoint_path, | ||
| config.get("base_model") or None, |
There was a problem hiding this comment.
Allow kernel provisioning during temporary HF offline windows
When _offline_window_if_unreachable detects only the Hugging Face endpoint is down, it temporarily sets the HF offline state and then calls this provisioner inside that window. package_installs_offline() consequently suppresses GitHub/PyPI kernel downloads too, so exporting a cached or local remote-code SSM model with a missing required kernel fails even when the package hosts remain reachable; keep the HF-only window from being interpreted as an operator-requested package-offline mode.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7c90c5b: the automatic HF offline window is now marked, and package installs ignore it. Only a user set HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE / UV_OFFLINE blocks provisioning.
| if package_installs_offline_env(): | ||
| return skip( | ||
| f"Unsloth: not installing {name} while offline " | ||
| "(UV_OFFLINE / HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE)." | ||
| ) |
There was a problem hiding this comment.
Preserve dry-run URL resolution while offline
With HF_HUB_OFFLINE, TRANSFORMERS_OFFLINE, or UV_OFFLINE set, this return runs even when dry_run=True, so unsloth install-kernels --dry-run prints no resolved wheel URL despite its documented purpose of printing the URL without installing anything. Offline and air-gapped image workflows commonly need exactly that output for prefetching; apply the offline installation guard only to non-dry runs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7c90c5b: dry run resolves and prints the URL even when offline; the offline early return only applies to real installs.
| if not _install(MAMBA_SSM, allow_source_build = mamba_ssm_required): | ||
| if mamba_ssm_fatal and _kernel_backend(_torch_env()) is not None: | ||
| raise RuntimeError( | ||
| f"Could not install mamba-ssm, required by this Mamba model. {offline_hint}" |
There was a problem hiding this comment.
Reject fatal Mamba loads on unsupported torch backends
When mamba_ssm_fatal is true because trusted remote code imports mamba_ssm unconditionally or the active Transformers has no native implementation, a CPU/XPU build or a failed torch probe makes _kernel_backend return None and suppresses this error. The worker then claims it will use a torch fallback that does not exist and proceeds until the modeling import fails cryptically; fatal loads should be rejected here regardless of whether a CUDA/ROCm installation was possible.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7c90c5b: a fatal Mamba load on a torch without CUDA or ROCm now raises a clear error instead of continuing into an import failure.
| # One overall deadline for every source build, CUDA as well as ROCm: run it through | ||
| # run_process_tree so a timeout also stops the compilers pip / uv started. | ||
| kwargs["timeout"] = SOURCE_BUILD_TIMEOUT |
There was a problem hiding this comment.
Avoid timing out valid non-ROCm source builds
This newly applies the 1800-second deadline to every CUDA source build, whereas the previous implementation deliberately left non-HIP builds unbounded because causal-conv1d can compile slowly on aarch64 and constrained builders. On a valid build taking more than 30 minutes, the process tree is killed and a required remote-code SSM model may become unloadable; retain a longer or platform-specific deadline rather than reusing the ROCm limit universally.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7c90c5b: CUDA source builds use their own 7200 s deadline (UNSLOTH_SOURCE_BUILD_TIMEOUT overrides), ROCm keeps 1800 s, and the lock wait is sized from the larger of the two.
…n CUDA build deadline - Export worker: run the malware and remote-code consent gates (transformers-free, no load-subdir scan) before provisioning SSM kernels, at startup and on each "load" command, so a blocked checkpoint never triggers a kernel build. _handle_load keeps its authoritative re-check through the shared helper. - Export offline window: mark an HF offline set only because the Hub was unreachable; package_installs_offline() and package_installs_offline_env() then honour only UV_OFFLINE, so required kernels can still come from GitHub / PyPI. An operator-set HF offline still blocks installs. - install_python_stack: re-probe a stale SSM extension while holding the kernel install lock and remove it only if it still fails the same way. - unsloth install-kernels --dry-run prints the wheel URL even offline. - ssm_runtime: a model that cannot load without mamba-ssm now fails clearly on a CPU / XPU torch instead of falling through to a torch path that cannot work. - CUDA source builds get their own 7200 s deadline (UNSLOTH_SOURCE_BUILD_TIMEOUT overrides); HIP keeps 1800 s; KERNEL_LOCK_WAIT covers the longer of the two.
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
#14268) ## Summary `studio/backend/tests/test_kernel_install.py::test_a_timed_out_build_stops_its_whole_process_tree` flakes in the `(Python 3.13, a-k)` shard (seen on #14240): ``` tests/test_kernel_install.py:1041: in test_a_timed_out_build_stops_its_whole_process_tree if stat.read().split()[2] == "Z": E ProcessLookupError: [Errno 3] No such process ``` ## Cause The test polls the killed grandchild until it is gone. That means `kill(pid, 0)` fails, or `/proc/<pid>/stat` shows a zombie, or that file is missing. The grandchild can be reaped between opening `/proc/<pid>/stat` and reading it. On Linux that read raises `ProcessLookupError` (ESRCH), not `FileNotFoundError`. So the test failed exactly when the process had already gone, which is the outcome it was waiting for. The product (`kernel_install.run_process_tree`) is fine. The poll came in with #13971. Reproduced directly: open `/proc/<pid>/stat` of a live child, kill and reap it, then read. The read raises `ProcessLookupError: [Errno 3] No such process`. ## Change Test-only: - **`_process_gone(pid)`:** the same three checks, with `(FileNotFoundError, ProcessLookupError)` both counted as gone. - **`test_a_process_reaped_while_its_stat_is_read_counts_as_gone`:** makes the race deterministic. `open` of the child's stat file kills and reaps the child right after opening, and `kill(pid, 0)` reports it alive, as at the start of the race. It is skipped where there is no procfs. ## Testing - **`studio/backend/tests/test_kernel_install.py`:** 119 passed. - **Sabotage:** with the helper back to catching only `FileNotFoundError`, the new test fails with `ProcessLookupError: [Errno 3] No such process`. That is the CI failure.
…h-zoo covers decode (#14148) Stacked on #13971. Pairs with unslothai/unsloth-zoo#1857. Qwen3.5 / Qwen3.6 / Qwen3-Next stop downloading causal-conv1d on demand when the installed unsloth-zoo runs their short conv in Triton for prefill, training and cached decode. ## Why unsloth-zoo#1857 adds a Triton `causal_conv1d_update` for GatedDeltaNet decode (the prefill / training conv was already Triton). On a Kaggle T4 (Qwen3.5-0.8B fp16) decode with it is within noise of the causal-conv1d package (19.79 vs 19.64 and 19.47 vs 19.20 tok/s, two lanes) at 16.5 us per call against 46-48 us for the package, with identical memory and tokens. The binary is then pure download cost for these models. ## Changes - `ssm_runtime.py`: Qwen3.5 / 3.6 / Qwen3-Next request causal-conv1d only when zoo cannot cover them: the installed zoo lacks the decode kernel (read from its source on `sys.path`, nothing imported), `UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D=1` is set, or the platform cannot run zoo's Triton conv (ROCm, macOS, no triton). The config check runs before the modeling source scan, since those modeling files mention causal_conv1d. Mixed configs and other conv users (LFM2, the Mamba families) still request it. - `clef_runtime.py`: Clef skips the install the same way and keeps the FLA TileLang guard. - An already installed causal-conv1d is left alone and still wins inside zoo. ## Tests `test_ssm_runtime.py`, `test_clef_fast_paths.py` (new cases fail on #13971's head and pass here), with `conftest.py` pinning the older-zoo answer so the suite does not depend on the host's zoo. 453 passed across the SSM, clef, export, training worker and install stack tests. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…nsloth-zoo runs their conv on Triton (#14160) Stacked on #13971. Pairs with unslothai/unsloth-zoo#1865 and the extension-free mamba-ssm wheel added in #14142. Mamba-2 hybrids (Nemotron-H, Falcon-H1, Granite-4.0-H, Bamba, Zamba2, Mamba2) install a 224 KB mamba-ssm wheel without its CUDA extension instead of the 230 to 594 MB mamba-ssm + causal-conv1d CUDA wheels, when unsloth-zoo can run their causal conv on Triton. ## Why On transformers 5.x these models only use mamba-ssm's Triton ops, never `selective_scan_cuda`. With unsloth-zoo#1865 the causal conv runs on Triton too. On a Colab T4 (torch 2.10, Falcon-H1-0.5B fp16 LoRA, three interleaved rounds) that route matches the CUDA wheels: train step +1.4% (inside the CUDA arm's own spread), decode +1.7% / +1.9%, prefill +0.7%, identical peak memory. ## Changes - `ssm_runtime.py` / training worker / export: the pure wheel is used, and causal-conv1d skipped, only when the config resolves to one of those six model types, no remote code is needed, torch is a CUDA build with Triton, transformers is 5.15 or newer, and the installed unsloth-zoo source carries the Triton drop-ins. `UNSLOTH_MAMBA_CUDA_KERNELS=1` keeps the CUDA wheels. - No source build on that route. If the pure wheel is unusable (definite 404, install failure, import failure), the load falls back to today's CUDA route (causal-conv1d, then CUDA mamba-ssm with the existing resolver and source build policy). The failure memo is keyed per wheel source, so a failed pure attempt never blocks the CUDA wheel, and both routes take the per-env lock one after the other. - `wheel_utils.mamba_ssm_pure_wheel_url()`. ## Tests `test_ssm_mamba2_triton.py` (24 tests; the fallback ones exercise the real `_install_kernel` with lock, memo and cleanup, only network and pip faked). 509 passed across the clef, export, kernel_install, SSM and training worker suites. Not covered: ROCm and macOS stay on the existing route by design; Windows triton-windows untested on a GPU; Mamba-1 models and transformers older than 5.15 keep the CUDA wheels. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Follow up to #13861 and #13808. An audit of the merged on demand SSM kernel change plus a T4 benchmark found a few gaps, fixed here.
Why
causal_conv1d_fnonly, so single token decode fell back to the torch update path. Training with trainable conv weights also allocates an fp32 dW scratch in the Triton backward, and packedseq_idxis not accepted by the zoo dispatcher under transformers 5.20.Changes
nemotron_h,falcon_h1,granitemoehybrid. Other Mamba families install best effort and continue on the torch path with a status message.adapter_config.json, noconfig.json) resolve kernel needs frombase_model_name_or_path; the trainingadapter_base_pinwins when set.transformers/models/<type>/modeling_*.pyas text, without importing transformers.transformers.models.<type>module was already imported, the inference worker asks for a restart and the orchestrator respawns it once.Tests
New and updated tests fail on main and pass here (
test_ssm_runtime.py,test_ssm_restart_respawn.py,test_export_ssm_kernels.py,test_clef_fast_paths.py,test_kernel_install.py,test_training_worker_flash_attn.py,test_ssm_kernels_install_python_stack.py,test_flash_attn_install_python_stack.py,test_windows_torch_flavor_invariant.py). Withtest_install_python_stack.pyandtest_cuda_repair.py: 966 passed after merging current main.Hardening (second commit)
unsloth install-kernels --without-gpu(orUNSLOTH_INSTALL_KERNELS_WITHOUT_GPU=1) installs GPU gated kernels on a GPU-less image builder. An already working kernel counts as success before any skip, skipped kernels are listed, and the exit code is unchanged (0) unless--strictis passed. The CLI respectsUV_OFFLINE/ HF offline variables and never falls back from uv to pip offline.modeling_*modules and the selected checkpoint's remote code modules from itsauto_map, matched on the exacttransformers_modulesnamespace.UV_OFFLINEcounts as offline for on-demand installs (no URL probes, source builds, or uv to pip fallback).Install robustness (platform matrix review)
UNSLOTH_SOURCE_BUILD_TIMEOUToverrides); a timeout kills the whole build tree.unsloth install-kernels --dry-runprints the resolved URL while offline.GPU checks (merge base vs head 4a6429a)
Kaggle T4, torch 2.11.0+cu130, Qwen3.5-0.8B fp16:
causal_conv1d_update_kernelengagedAMD gfx1151 (torch 2.11.0+rocm7.13.0): Qwen3.5 LoRA losses within 1.2e-4 relative (head vs merge commit bit identical), peak 2.389 GB both, backend suites 262/262 and 275/275 passing.