-
Notifications
You must be signed in to change notification settings - Fork 34
[FEAT][kernels]: add ROCm FlashAttention backend #104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Copyright (c) 2026 RL-Kernel Contributors | ||
|
|
||
| import torch | ||
| import torch.nn.functional as F | ||
|
|
||
|
|
||
| class NativeAttentionOp: | ||
| """PyTorch SDPA fallback for FlashAttention-layout tensors.""" | ||
|
|
||
| def __call__( | ||
| self, | ||
| q: torch.Tensor, | ||
| k: torch.Tensor, | ||
| v: torch.Tensor, | ||
| dropout_p: float = 0.0, | ||
| softmax_scale: float | None = None, | ||
| causal: bool = False, | ||
| ) -> torch.Tensor: | ||
| # Convert FlashAttention layout to PyTorch SDPA layout: | ||
| # (batch, seqlen, nheads, headdim) -> (batch, nheads, seqlen, headdim) | ||
| q_ref = q.transpose(1, 2) | ||
| k_ref = k.transpose(1, 2) | ||
| v_ref = v.transpose(1, 2) | ||
|
|
||
| q_head_num = q_ref.shape[1] | ||
| k_head_num = k_ref.shape[1] | ||
| if k_head_num != v_ref.shape[1]: | ||
| raise ValueError("k and v must have the same number of heads") | ||
|
|
||
| if q_head_num != k_head_num: | ||
| if q_head_num % k_head_num != 0: | ||
| raise ValueError("q heads must be divisible by k/v heads for GQA/MQA") | ||
| repeat = q_head_num // k_head_num | ||
| k_ref = k_ref.repeat_interleave(repeat, dim=1) | ||
| v_ref = v_ref.repeat_interleave(repeat, dim=1) | ||
|
|
||
| out = F.scaled_dot_product_attention( | ||
| q_ref, | ||
| k_ref, | ||
| v_ref, | ||
| dropout_p=dropout_p, | ||
| is_causal=causal, | ||
| scale=softmax_scale, | ||
| ) | ||
| return out.transpose(1, 2) | ||
|
|
||
|
|
||
| __all__ = ["NativeAttentionOp"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Copyright (c) 2026 RL-Kernel Contributors | ||
|
|
||
| from .flash_attn import RocmFlashAttentionOp | ||
|
|
||
| __all__ = [ | ||
| "RocmFlashAttentionOp", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Copyright (c) 2026 RL-Kernel Contributors | ||
|
|
||
| import os | ||
|
|
||
| import torch | ||
|
|
||
| from rl_engine.utils.logger import logger | ||
|
|
||
| _MAX_TESTED_ROCM_TRITON_HEAD_DIM = 512 | ||
|
|
||
|
|
||
| def _select_flash_attn_backend() -> str: | ||
|
FED4 marked this conversation as resolved.
|
||
| """Select the installed FlashAttention ROCm backend.""" | ||
| return "triton" | ||
|
|
||
|
|
||
| class RocmFlashAttentionOp: | ||
| """ | ||
| Standard FlashAttention wrapper for ROCm. | ||
| Demonstrates the reference structure for adding new operator families. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| if torch.version.hip is None: | ||
| raise RuntimeError("RocmFlashAttentionOp requires a ROCm PyTorch build.") | ||
|
|
||
| backend = _select_flash_attn_backend() | ||
| if backend == "triton": | ||
| # flash-attn selects the ROCm CK/Triton backend at import time. | ||
| os.environ["FLASH_ATTENTION_TRITON_AMD_ENABLE"] = "TRUE" | ||
| try: | ||
| from flash_attn import flash_attn_func | ||
|
|
||
| self.op = flash_attn_func | ||
| logger.info("Successfully linked to external flash_attn library (%s backend).", backend) | ||
| except (ImportError, OSError, RuntimeError) as exc: | ||
| raise RuntimeError( | ||
| "ROCm FlashAttention requires a ROCm-compatible flash-attn installation. " | ||
| "See docs/getting_started/installation.md#rocm-backend." | ||
| ) from exc | ||
|
|
||
| def __call__( | ||
|
FED4 marked this conversation as resolved.
|
||
| self, | ||
| q: torch.Tensor, | ||
| k: torch.Tensor, | ||
| v: torch.Tensor, | ||
| dropout_p: float = 0.0, | ||
| softmax_scale: float | None = None, | ||
|
FED4 marked this conversation as resolved.
|
||
| causal: bool = False, | ||
| ) -> torch.Tensor: | ||
| """ | ||
| Standard attention forward pass. | ||
| Args: | ||
| q: (batch, seqlen, nheads, headdim) | ||
| k: (batch, seqlen, nheads_k, headdim) | ||
| v: (batch, seqlen, nheads_k, headdim) | ||
| """ | ||
| valid_dtypes = (torch.float16, torch.bfloat16) | ||
| if ( | ||
| q.dtype not in valid_dtypes | ||
| or k.dtype not in valid_dtypes | ||
| or v.dtype not in valid_dtypes | ||
| ): | ||
| raise TypeError("FlashAttention requires FP16 or BF16 for q/k/v") | ||
| # PyTorch uses the CUDA device API for both CUDA and ROCm tensors. | ||
| if not (q.is_cuda and k.is_cuda and v.is_cuda): | ||
| raise ValueError("Inputs must be on a CUDA/ROCm GPU device") | ||
| if not (q.device == k.device == v.device): | ||
| raise ValueError("q, k, and v must be on the same device") | ||
| if q.ndim != 4 or k.ndim != 4 or v.ndim != 4: | ||
| raise ValueError( | ||
| "q, k, and v must be rank-4 tensors: (batch, seqlen, nheads, head_dim)" | ||
| ) | ||
|
|
||
| head_dim = q.shape[-1] | ||
| if head_dim == 0: | ||
| raise ValueError("head_dim must be positive") | ||
| if k.shape[-1] != head_dim or v.shape[-1] != head_dim: | ||
| raise ValueError("q, k, and v must have the same head_dim") | ||
| if head_dim > _MAX_TESTED_ROCM_TRITON_HEAD_DIM: | ||
| raise NotImplementedError( | ||
| "RL-Kernel's ROCm FlashAttention wrapper currently supports " | ||
| f"head_dim <= {_MAX_TESTED_ROCM_TRITON_HEAD_DIM}; got {head_dim}" | ||
| ) | ||
|
|
||
| if softmax_scale is None: | ||
| softmax_scale = q.shape[-1] ** -0.5 | ||
|
|
||
| q, k, v = q.contiguous(), k.contiguous(), v.contiguous() | ||
|
|
||
| return self.op(q, k, v, dropout_p=dropout_p, softmax_scale=softmax_scale, causal=causal) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Copyright (c) 2026 RL-Kernel Contributors | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import importlib.util | ||
| import os | ||
|
|
||
|
|
||
| def _fail(message: str) -> None: | ||
| raise SystemExit(f"ERROR: {message}") | ||
|
|
||
|
|
||
| def main() -> None: | ||
| try: | ||
| import torch | ||
| except ImportError as exc: | ||
| _fail(f"PyTorch is not installed: {exc}") | ||
|
|
||
| if torch.version.hip is None: | ||
| _fail(f"PyTorch is not a ROCm build: torch={torch.__version__}") | ||
|
|
||
| if not torch.cuda.is_available(): | ||
| _fail("ROCm GPU is not available to PyTorch") | ||
|
|
||
| device_name = torch.cuda.get_device_name(0) | ||
| triton_available = importlib.util.find_spec("triton") is not None | ||
| flash_attn_func_available = False | ||
| # flash-attn selects the ROCm CK/Triton backend at import time. | ||
| os.environ["FLASH_ATTENTION_TRITON_AMD_ENABLE"] = "TRUE" | ||
| try: | ||
| from flash_attn import flash_attn_func | ||
| except (ImportError, OSError, RuntimeError) as exc: | ||
| flash_attn_status = f"not available ({exc})" | ||
| else: | ||
| flash_attn_func_available = flash_attn_func is not None | ||
| flash_attn_status = "available" if flash_attn_func_available else "not available" | ||
|
|
||
| print("backend availability:") | ||
| print( | ||
| " ROCm PyTorch runtime: " | ||
| f"available (torch={torch.__version__}, hip={torch.version.hip}, GPU={device_name})" | ||
| ) | ||
| print(" PyTorch SDPA fallback: available") | ||
| print(f" Triton package: {'available' if triton_available else 'not available'}") | ||
| print(f" flash-attn AMD Triton: {flash_attn_status}") | ||
| print(" ROCm CK: not selected by this checker") | ||
|
|
||
| if not flash_attn_func_available: | ||
| _fail("flash_attn AMD Triton backend is required but could not be imported") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.