Skip to content

Studio flashattn - #5435

Closed
Datta0 wants to merge 42 commits into
unslothai:mainfrom
Datta0:studio_flashattn
Closed

Datta0 wants to merge 42 commits into
unslothai:mainfrom
Datta0:studio_flashattn

Conversation

@Datta0

@Datta0 Datta0 commented May 15, 2026

Copy link
Copy Markdown
Contributor
  • install flash-attn at setup time if prebuilt wheels available
  • install flash-attn at train time if the seq len > 16k
  • install flash-linear-attn like we do for causal-conv1d and mamba-ssm at train time if the model needs it.
    For anything prefer wheels over pypi

@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 refactors the installation logic for optional training kernels—including flash-attn, causal-conv1d, mamba-ssm, and the newly added flash-linear-attention—into a centralized install_optional_kernel utility driven by a KernelPackageSpec dataclass. Additionally, the sequence length threshold for triggering flash-attn installation has been reduced from 32,768 to 16,384. Feedback was provided to enhance the robustness of the PyPI installation path within the new utility by implementing a fallback from uv to pip upon failure, ensuring consistency with other installation methods in the codebase.

Comment thread studio/backend/utils/wheel_utils.py Outdated
Comment on lines +431 to +449
pypi_cmd = _pypi_install_command(
spec,
python_executable = python_executable,
use_uv = use_uv,
uv_needs_system = uv_needs_system,
is_hip = is_hip,
)

run_kwargs: dict[str, object] = {
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"text": True,
"env": child_env_without_native_path_secret(),
}
if is_hip:
run_kwargs["timeout"] = 1800

try:
result = run(pypi_cmd, **run_kwargs)

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.

medium

The PyPI installation logic in install_optional_kernel currently lacks a fallback mechanism if uv is requested but fails (e.g., due to environment-specific issues or missing flags). This is inconsistent with the install_wheel function (line 249), which robustly tries uv first and then falls back to pip.

To maintain separation of concerns and avoid coupling with external installer scripts, this logic should be implemented directly within the utility. I suggest refactoring this section to attempt the installation with uv (if available) and then fall back to pip on failure, ensuring that the training process isn't interrupted by uv-specific issues.

    run_kwargs: dict[str, object] = {
        "stdout": subprocess.PIPE,
        "stderr": subprocess.STDOUT,
        "text": True,
        "env": child_env_without_native_path_secret(),
    }
    if is_hip:
        run_kwargs["timeout"] = 1800

    # Try uv first if requested and available, then fall back to pip
    if use_uv and shutil.which("uv"):
        pypi_cmd = _pypi_install_command(
            spec,
            python_executable = python_executable,
            use_uv = True,
            uv_needs_system = uv_needs_system,
            is_hip = is_hip,
        )
        try:
            result = run(pypi_cmd, **run_kwargs)
            if result.returncode == 0:
                _logger.info("Installed %s from PyPI using uv", spec.display_name)
                return True
            _logger.warning("uv failed to install %s from PyPI; falling back to pip", spec.display_name)
        except subprocess.TimeoutExpired:
            raise
        except Exception as exc:
            _logger.warning("uv encountered an error: %s; falling back to pip", exc)

    pypi_cmd = _pypi_install_command(
        spec,
        python_executable = python_executable,
        use_uv = False,
        uv_needs_system = uv_needs_system,
        is_hip = is_hip,
    )
    try:
        result = run(pypi_cmd, **run_kwargs)
References
  1. Avoid coupling modules by importing installer script logic into backend utilities. If a utility needs similar functionality, implement it within the utility itself to maintain separation of concerns.

@Datta0
Datta0 force-pushed the studio_flashattn branch from 05465fc to b49a321 Compare May 15, 2026 08:17
@mmathew23

Copy link
Copy Markdown
Contributor

einops is a dep of flash-attn and the wheels -no-deps install doesn't pull it in, so we could install manually as a workaround. Maybe add a CI check to see if it dep list ever changes?

_FLASH_ATTN_RUNTIME_MIN_SEQ_LEN = 32768 but description notes "install flash-attn at train time if the seq len > 16k" so I want to confirm if the limit is 16k or 32k.

CC says gemini's concern is legitimate. If we want pip to be a uv fallback on failure we should address.

@Datta0
Datta0 marked this pull request as ready for review May 19, 2026 04:57
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@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: 5ef59a8a59

ℹ️ 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/training/worker.py Outdated
Comment on lines +208 to +213
if spec in (FLASH_ATTN_SPEC, FLASH_LINEAR_ATTN_SPEC) and is_blackwell():
_send_status(
event_queue,
f"Skipping {spec.display_name} install: Blackwell GPU detected (sm_100+); no compatible prebuilt wheel",
)
continue

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 Don't skip PyPI-only FLA on Blackwell

When a Blackwell GPU is present and the selected model needs the FLA path (for example Qwen3-Next/Qwen3.5), this guard skips FLASH_LINEAR_ATTN_SPEC before install_optional_kernel can run. Unlike FLASH_ATTN_SPEC, the flash-linear-attention spec is PyPI-only (build_wheel_url returns None), so the “no compatible prebuilt wheel” rationale does not apply; this leaves those models without the newly required flash-linear-attention package specifically on Blackwell machines.

Useful? React with 👍 / 👎.

Datta0 and others added 7 commits May 19, 2026 05:29
…tall_optional_kernel

Adds three targeted tests for install_optional_kernel branches that were not
previously asserted on the new shared helper:

* ROCm with no hipcc on PATH returns False without invoking run and surfaces
  a hipcc status message.
* ROCm with hipcc and a resolved gcc install dir injects
  --gcc-install-dir into HIPCC_COMPILE_FLAGS_APPEND on the subprocess env
  and applies the 1800s HIP source build timeout.
* Direct wheel install scrubs UNSLOTH_NATIVE_PATH_LEASE_SECRET from the
  subprocess env so the native path lease secret never leaks into pip or uv.
The production flash-linear-attention install path lives in
_ensure_flash_linear_attention_unconditional in
studio/backend/core/training/worker.py and does not go through
install_optional_kernel, so FLASH_LINEAR_ATTN_SPEC was only ever
referenced by the wheel_utils unit tests.

Removes the dead export and re-points the affected tests at an
in-test synthetic plain-PyPI spec via the new _plain_pypi_spec
helper. Test coverage of the plain-PyPI install branches in
install_optional_kernel is unchanged.

@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: adb78393b6

ℹ️ 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 +276 to +278
try:
__import__(import_name)
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 Treat broken installed kernels as not importable

When setup runs with a stale or partially broken flash_attn package whose top-level import raises something other than ImportError (for example an OSError/RuntimeError from ABI or CUDA library initialization), this helper lets the exception propagate before it can check/install the compatible prebuilt wheel. The previous setup path ran python -c 'import flash_attn' and treated any non-zero result as missing, so these environments now abort installation instead of repairing flash-attn.

Useful? React with 👍 / 👎.

Addresses several findings from a 20-reviewer pass over PR unslothai#5435:

* wheel_utils._package_is_importable now treats any import failure as
  "missing", not just ImportError. An ABI-broken native package such as
  flash_attn after a torch bump raises OSError or RuntimeError on
  import and would otherwise crash the helper before the wheel install
  or fallback path could run. Logs a warning when the broad branch
  fires so users still see why the package is being re-installed.

* install_optional_kernel now tails the installer stdout on a wheel
  install failure when no PyPI fallback is allowed (setup-time flow).
  Previously stdout was only sent to _logger.warning so setup users
  did not see the resolver, network, cache, or ABI error that caused
  the wheel install to fail.

* install_python_stack run() pip_install_try() and the USE_UV branch
  of pip_install() now scrub UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET
  from the child env via child_env_without_native_path_secret(). The
  optional-kernel subprocesses were already sanitized in the original
  PR; this extends the same hygiene to the generic install subprocesses
  in the same setup pipeline.

* _ensure_flash_attn() now reads the install_optional_kernel boolean
  return value and emits "Continuing without flash-attn" when the
  wheel install fails. The previous flow lost that final status line.

* Adds a regression test for the broadened import-failure branch.

@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: cde405fcf2

ℹ️ 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/wheel_utils.py Outdated
Comment on lines +114 to +117
if result.returncode == 0 and any(
line.strip() for line in result.stdout.splitlines()
):
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 Respect the process GPU mask before returning true

In environments where CUDA_VISIBLE_DEVICES is set to an empty mask or to non-NVIDIA/ROCm devices, nvidia-smi --query-gpu=name can still list the host's physical NVIDIA GPUs even though none are visible to this worker process. Because this returns True before the torch visibility fallback runs, the new flash-attn/FLA gates can try to install NVIDIA-only kernels for CPU-masked or AMD-selected runs instead of skipping them as intended by the docstring and callers.

Useful? React with 👍 / 👎.

@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: df4f898278

ℹ️ 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".

uv_needs_system = uv_needs_system,
run = run,
):
if result.returncode == 0:

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 Recheck the kernel after a successful reinstall

When _package_is_importable() returned false because an already-installed native extension is broken, treating any installer exit code 0 as success can leave the environment unrepaired: the direct-wheel commands omit a reinstall flag, and python -m pip install --help describes --force-reinstall as “Reinstall all packages even if they are already up-to-date,” so a same-version installed wheel can be skipped while this returns True without verifying that import flash_attn now works. This affects stale/partially broken flash-attn installs at the same wheel version, causing setup/runtime to stop trying even though the package remains unusable.

Useful? React with 👍 / 👎.

Datta0 and others added 4 commits June 5, 2026 15:52
# Conflicts:
#	studio/backend/tests/test_training_worker_flash_attn.py
#	studio/backend/utils/wheel_utils.py
#	studio/install_python_stack.py
#	tests/python/test_flash_attn_install_python_stack.py

@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: b1f7c724c4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +483 to +488
if has_blackwell_gpu():
_send_status(
event_queue,
"Skipping flash-linear-attention install: Blackwell GPU detected",
)
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 Respect the selected GPU before skipping FLA

When a mixed-GPU host has any Blackwell card but the worker is pinned via resolved_gpu_ids/CUDA_VISIBLE_DEVICES to a non-Blackwell NVIDIA GPU, this new gate still skips FLA because has_blackwell_gpu() queries nvidia-smi for all physical GPUs and does not filter by the process mask. That makes compatible runs on the selected non-Blackwell GPU miss the FLA fast path before the installer or version check can run.

Useful? React with 👍 / 👎.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@danielhanchen danielhanchen added superseded# still-needed# Stale but the problem is still present on main; review it refactor# and removed superseded# labels Sep 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Main has moved on since this branch: studio/install_python_stack.py::_ensure_flash_attn now installs and import-verifies flash-attn at setup, and the Blackwell short-circuit in the worker path was deliberately removed, so this re-adds it and also drops the runtime threshold from 32768 to 16384 which makes many more training runs install mid-session. Could you rebase and confirm which of the NVIDIA gate, the shared install_optional_kernel refactor and the threshold change you still want, ideally split so the threshold change lands on its own?

@danielhanchen

Copy link
Copy Markdown
Member

Closing this one. Checked the diff against current main (49b48434) and most of it has either landed already or targets code that no longer exists.

What is already on main:

  • Setup-time flash-attn install. install_python_stack.py:7708 _ensure_flash_attn, wired in at :11113. Main also added post-install import verification (_flash_attn_importable, :7669) and removal of a wheel that installs but will not import (_remove_rejected_flash_attn, :7688) via Studio: verify the flash-attn import after installing it #8465. This branch is studio_flashattn, which already merged once as [Studio] Install flash attn at setup time for linux #4979, so the setup-time half of the diff is reading back its own merged work.
  • Shared optional-kernel installer. Main grew the worker-side helper into the canonical one instead: worker.py:1311 _install_package_wheel_first plus _attempt_package_install. It does strictly more than install_optional_kernel here, with an offline short-circuit, out-of-process import verification (_is_importable_isolated), uninstall-before-fallback, and a finally: _reject_install(...) on every exit path. Taking the version in this PR would drop all four.
  • Subprocess env hygiene. wheel_utils.py:314 and :331 already pass child_env_without_native_path_secret(), so the tests asserting on env_in_kwargs are written against a shape main no longer has.

What is obsolete:

One real gap survives and is worth its own PR. _ensure_flash_attn_for_long_context (worker.py:1991) gates only on seq length, an env skip, and sys.platform.startswith("linux"). On ROCm, XPU or CPU-only, flash_attn_wheel_url returns None and _attempt_package_install falls through to the plain PyPI branch (worker.py:1441), which is a CUDA source build on a non-CUDA host. The setup-time path is unaffected since it has no PyPI fallback. That fix should reuse utils/hardware/nvidia.py rather than add a third GPU detector, since install_python_stack.py:2594 _has_usable_nvidia_gpu already covers Windows driver paths and the procfs fallback that a plain nvidia-smi check misses.

The runtime threshold change (32768 to 16384, and < to <=) is also still unmerged and is a real design question rather than a cleanup, so it deserves a standalone PR where the 16k versus 32k intent can be answered directly. Same for the einops and --no-deps point raised in review, which is the one idea here that main has neither adopted nor rejected.

We are picking these up, so no action needed on your side. Thanks for the work on this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

conflicts# new-feature# refactor# still-needed# Stale but the problem is still present on main; review it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants