[Diffusion]: Diffusion Ring Attention support (#273)

Signed-off-by: mxuax <mxuax@connect.ust.hk>
Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Jiangyun Zhu <riverclouds.zhu@qq.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2025-12-31 14:26:30 +00:00
1 parent 9c7de5373a
commit 680742bc33
23 files changed
+1888 -186

No files matched your search

@@ -0,0 +1 @@
# Ring attention backend components
@@ -0,0 +1,59 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Copyright (c) 2024, Jiarui Fang.
# Adapted from https://github.com/feifeibear/long-context-attention
# test if flash_attn is available
try:
import flash_attn # noqa: F401
from flash_attn.flash_attn_interface import _flash_attn_backward, _flash_attn_forward # noqa: F401
HAS_FLASH_ATTN = True
except ImportError:
HAS_FLASH_ATTN = False
try:
from flash_attn_interface import _flash_attn_backward as flash_attn_func_hopper_backward # noqa: F401
from flash_attn_interface import _flash_attn_forward as flash_attn_forward_hopper # noqa: F401
from flash_attn_interface import flash_attn_func as flash3_attn_func # noqa: F401
HAS_FLASH_ATTN_HOPPER = True
except ImportError:
HAS_FLASH_ATTN_HOPPER = False
try:
from flashinfer.prefill import single_prefill_with_kv_cache # noqa: F401
HAS_FLASHINFER = True
except ImportError:
HAS_FLASHINFER = False
try:
import aiter # noqa: F401
from aiter import flash_attn_func as flash_attn_func_aiter # noqa: F401
HAS_AITER = True
except ImportError:
HAS_AITER = False
try:
import sageattention # noqa: F401
HAS_SAGE_ATTENTION = True
except ImportError:
HAS_SAGE_ATTENTION = False
try:
import spas_sage_attn # noqa: F401
HAS_SPARSE_SAGE_ATTENTION = True
except ImportError:
HAS_SPARSE_SAGE_ATTENTION = False
try:
import torch_npu # noqa: F401
HAS_NPU = True
except ImportError:
HAS_NPU = False
@@ -0,0 +1,283 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024, Jiarui Fang.
# Adapted from https://github.com/feifeibear/long-context-attention
import math
import torch
from .ring_globals import HAS_AITER, HAS_FLASH_ATTN, HAS_FLASH_ATTN_HOPPER, HAS_FLASHINFER, HAS_NPU
_scaled_dot_product_flash_attention = torch.ops.aten._scaled_dot_product_flash_attention
_scaled_dot_product_efficient_attention = torch.ops.aten._scaled_dot_product_efficient_attention
try:
import torch_musa # noqa: F401
_scaled_dot_product_flash_attention = torch.ops.aten._scaled_dot_product_attention_flash_musa
_scaled_dot_product_efficient_attention = None
except ModuleNotFoundError:
pass
if HAS_AITER:
from aiter import flash_attn_func as flash_attn_func_aiter
if HAS_FLASH_ATTN:
import flash_attn
from flash_attn.flash_attn_interface import _flash_attn_forward
if HAS_FLASH_ATTN_HOPPER:
from flash_attn_interface import _flash_attn_backward as flash_attn_func_hopper_backward
from flash_attn_interface import _flash_attn_forward as flash_attn_forward_hopper
from flash_attn_interface import flash_attn_func as flash3_attn_func
else:
flash_attn_forward_hopper = None
flash_attn_func_hopper_backward = None
flash3_attn_func = None
if HAS_FLASHINFER:
from flashinfer.prefill import single_prefill_with_kv_cache
_LOG2_E = math.log2(math.e)
if HAS_NPU:
import torch_npu
def pytorch_attn_forward(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
dropout_p=0.0,
softmax_scale=None,
causal=True,
window_size=(-1, -1),
softcap=None,
alibi_slopes=None,
return_softmax=False,
op_type="efficient",
):
assert op_type in ["flash", "efficient"], f"Invalid op_type: {op_type}"
"""
q shape (bs, seqlen, nhead, hs)
k shape (bs, seqlen, nhead, hs)
v shape (bs, seqlen, nhead, hs)
"""
# Fallback logic: Flash Attention does not support float32.
# If op_type is 'flash' but dtype is float32, force 'efficient'.
if op_type == "flash" and q.dtype == torch.float32:
op_type = "efficient"
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
if op_type == "flash":
out, lse = _scaled_dot_product_flash_attention(
q,
k,
v,
dropout_p=dropout_p,
is_causal=causal,
scale=softmax_scale,
)[:2]
elif op_type == "efficient":
out, lse = _scaled_dot_product_efficient_attention(
q,
k,
v,
attn_bias=None,
compute_log_sumexp=True,
dropout_p=dropout_p,
is_causal=causal,
scale=softmax_scale,
)[:2]
else:
raise ValueError(f"Invalid op_type: {op_type}")
out = out.transpose(1, 2)
lse = lse.to(q.dtype)
return out, lse
def flash_attn_forward(
q,
k,
v,
dropout_p=0.0,
softmax_scale=None,
causal=False,
window_size=(-1, -1),
softcap=None,
alibi_slopes=None,
return_softmax=False,
):
assert HAS_FLASH_ATTN, "FlashAttention is not available"
if softmax_scale is None:
softmax_scale = q.shape[-1] ** (-0.5)
if flash_attn.__version__ < "2.6.3":
block_out, _, _, _, _, block_lse, _, _ = _flash_attn_forward(
q,
k,
v,
dropout_p=dropout_p,
softmax_scale=softmax_scale,
causal=causal,
window_size=window_size,
softcap=softcap,
alibi_slopes=alibi_slopes,
return_softmax=return_softmax,
)
else:
block_out, block_lse, _, _ = _flash_attn_forward(
q,
k,
v,
dropout_p=dropout_p,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=window_size[0],
window_size_right=window_size[1],
softcap=softcap,
alibi_slopes=alibi_slopes,
return_softmax=return_softmax,
)
return block_out, block_lse
def flash_attn3_func_forward(
q, k, v, dropout_p, softmax_scale, causal, window_size, softcap, alibi_slopes, return_softmax
):
assert HAS_FLASH_ATTN_HOPPER
# current signature of flash_attn_forward_hopper:
# (q, k, v, softmax_scale, causal, window_size, descale_q=None, descale_k=None, descale_v=None, gqa_parallel=False)
out, softmax_lse, *unused = flash_attn_forward_hopper(
q=q,
k=k,
v=v,
k_new=None,
v_new=None,
qv=None,
out=None,
cu_seqlens_q=None,
cu_seqlens_k=None,
cu_seqlens_k_new=None,
seqused_q=None,
seqused_k=None,
max_seqlen_q=None,
max_seqlen_k=None,
page_table=None,
kv_batch_idx=None,
leftpad_k=None,
rotary_cos=None,
rotary_sin=None,
seqlens_rotary=None,
q_descale=None,
k_descale=None,
v_descale=None,
softmax_scale=softmax_scale,
causal=False,
window_size=(-1, -1),
attention_chunk=0,
softcap=0.0,
rotary_interleaved=True,
scheduler_metadata=None,
num_splits=0,
pack_gqa=None,
sm_margin=0,
)
return out, softmax_lse
def flash_attn_forward_aiter(
q,
k,
v,
dropout_p=0.0,
softmax_scale=None,
causal=False,
window_size=(-1, -1),
softcap=None,
alibi_slopes=None,
return_softmax=False,
):
assert HAS_AITER, "Aiter is not available"
block_out, block_lse = flash_attn_func_aiter(
q,
k,
v,
dropout_p=dropout_p,
softmax_scale=softmax_scale,
causal=causal,
window_size=window_size,
alibi_slopes=alibi_slopes,
return_lse=True,
)
return block_out, block_lse
def flashinfer_attn_forward(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
dropout_p: float = 0.0,
softmax_scale: float | None = None,
causal: bool = False,
window_size: tuple[int, int] = (-1, -1),
softcap: float | None = None,
alibi_slopes: torch.Tensor | None = None,
return_softmax: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
assert HAS_FLASHINFER, "FlashInfer is not available"
if q.ndim == 4:
if q.shape[0] > 1:
raise ValueError("batch size > 1 is not supported")
out, lse = single_prefill_with_kv_cache(
q[0],
k[0],
v[0],
sm_scale=softmax_scale,
causal=causal,
logits_soft_cap=softcap,
window_left=window_size[0],
return_lse=True,
)
lse = lse.transpose(0, 1)
out, lse = out.unsqueeze(0), lse.unsqueeze(0)
elif q.ndim == 3:
out, lse = single_prefill_with_kv_cache(
q,
k,
v,
sm_scale=softmax_scale,
causal=causal,
logits_soft_cap=softcap,
window_left=window_size[0],
return_lse=True,
)
lse = lse.transpose(0, 1)
else:
raise ValueError(f"Invalid input shape: {q.shape}")
lse = lse / _LOG2_E
return out, lse
def npu_attn_forward(q, k, v, softmax_scale=None, layout="BSND"):
assert HAS_NPU, "torch_npu is not available"
softmax_scale = q.shape[-1] ** (-0.5)
block_out, block_lse = torch_npu.npu_fused_infer_attention_score(
q,
k,
v,
num_heads=q.shape[-2],
input_layout=layout,
scale=softmax_scale,
softmax_lse_flag=True,
pre_tokens=65535,
next_tokens=65535,
)
return block_out, block_lse.squeeze(dim=-1)
@@ -0,0 +1,169 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Copyright (c) 2024, Jiarui Fang.
# Adapted from https://github.com/feifeibear/long-context-attention
from collections.abc import Callable
from enum import Enum
from functools import partial
import torch
from .ring_globals import (
HAS_NPU,
HAS_SAGE_ATTENTION,
HAS_SPARSE_SAGE_ATTENTION,
)
from .ring_kernels import (
flash_attn3_func_forward,
flash_attn_forward,
flash_attn_forward_aiter,
flashinfer_attn_forward,
pytorch_attn_forward,
)
if HAS_SAGE_ATTENTION:
import sageattention
if HAS_SPARSE_SAGE_ATTENTION:
from spas_sage_attn.autotune import SparseAttentionMeansim
if HAS_NPU:
from torch_npu import npu_fused_infer_attention_score
class AttnType(Enum):
AITER = "aiter"
FA = "fa"
FA3 = "fa3"
FLASHINFER = "flashinfer"
TORCH = "torch"
SAGE_AUTO = "sage_auto"
SAGE_FP16 = "sage_fp16"
SAGE_FP16_TRITON = "sage_fp16_triton"
SAGE_FP8 = "sage_fp8"
SAGE_FP8_SM90 = "sage_fp8_sm90"
SPARSE_SAGE = "sparse_sage"
NPU = "npu"
@classmethod
def from_string(cls, s: str):
for member in cls:
if member.value == s:
return member
raise ValueError(f"'{s}' is not a valid {cls.__name__}")
def select_flash_attn_impl(
impl_type: AttnType,
stage: str = "fwd-only",
attn_processor: torch.nn.Module | None = None,
) -> Callable[..., tuple[torch.Tensor, torch.Tensor | None]]:
"""Select attention implementation for forward pass (inference only).
Args:
impl_type: The attention implementation type.
stage: Must be "fwd-only" (backward not supported for inference).
attn_processor: Optional custom attention processor.
Returns:
Callable[..., tuple[torch.Tensor, torch.Tensor | None]]: The attention
forward function for the specified implementation.
"""
if stage != "fwd-only":
raise ValueError(f"Only 'fwd-only' stage is supported for inference. Got: {stage}")
if impl_type == AttnType.AITER:
return flash_attn_forward_aiter
elif impl_type == AttnType.FA:
return flash_attn_forward
elif impl_type == AttnType.FA3:
return flash_attn3_func_forward
elif impl_type == AttnType.FLASHINFER:
return flashinfer_attn_forward
elif impl_type == AttnType.TORCH:
return pytorch_attn_forward
elif impl_type == AttnType.SAGE_AUTO:
if not HAS_SAGE_ATTENTION:
raise ImportError("SageAttention is not available!")
return partial(
sageattention.sageattn,
tensor_layout="NHD",
return_lse=True,
)
elif impl_type == AttnType.SAGE_FP16:
if not HAS_SAGE_ATTENTION:
raise ImportError("SageAttention is not available!")
return partial(
sageattention.sageattn_qk_int8_pv_fp16_cuda,
pv_accum_dtype="fp32",
tensor_layout="NHD",
return_lse=True,
)
elif impl_type == AttnType.SAGE_FP16_TRITON:
if not HAS_SAGE_ATTENTION:
raise ImportError("SageAttention is not available!")
return partial(
sageattention.sageattn_qk_int8_pv_fp16_triton,
tensor_layout="NHD",
return_lse=True,
)
elif impl_type == AttnType.SAGE_FP8:
if not HAS_SAGE_ATTENTION:
raise ImportError("SageAttention is not available!")
return partial(
sageattention.sageattn_qk_int8_pv_fp8_cuda,
pv_accum_dtype="fp32+fp32",
tensor_layout="NHD",
return_lse=True,
)
elif impl_type == AttnType.SAGE_FP8_SM90:
if not HAS_SAGE_ATTENTION:
raise ImportError("SageAttention is not available!")
return partial(
sageattention.sageattn_qk_int8_pv_fp8_cuda_sm90,
pv_accum_dtype="fp32+fp32",
tensor_layout="NHD",
return_lse=True,
)
elif impl_type == AttnType.SPARSE_SAGE:
if not HAS_SPARSE_SAGE_ATTENTION:
raise ImportError("SparseSageAttention is not available!")
if not isinstance(attn_processor, SparseAttentionMeansim):
raise ImportError("SparseSageAttention is only available with a SparseAttentionProcessor class passed in")
def fn(q, k, v, causal=False, softmax_scale=None, *args, **kwargs):
return (
attn_processor(
q,
k,
v,
is_causal=causal,
scale=softmax_scale,
tensor_layout="NHD",
),
None,
)
return fn
elif impl_type == AttnType.NPU:
if not HAS_NPU:
raise ImportError("torch_npu is not available!")
return npu_fused_infer_attention_score
elif attn_processor is not None:
return attn_processor
else:
raise ValueError(f"Unknown flash attention implementation: {impl_type}")
@@ -0,0 +1,173 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024, Jiarui Fang.
# Adapted from https://github.com/feifeibear/long-context-attention
import torch
import torch.nn.functional as F
__all__ = ["update_out_and_lse", "flatten_varlen_lse", "unflatten_varlen_lse"]
# Remove torch.jit.script for debugging and flexible shape handling
def _update_out_and_lse(
out: torch.Tensor,
lse: torch.Tensor,
block_out: torch.Tensor,
block_lse: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
block_out = block_out.to(torch.float32)
B, S, H, D = out.shape
# --- Shape Correction Logic for block_lse ---
# Goal: block_lse should be (B, S, H, 1) to match out (B, S, H, D)
# Debug info
# print(f"DEBUG _update: out={out.shape}, block_lse={block_lse.shape}")
# Case 0: If block_lse is already 4D, check if it matches
if block_lse.dim() == 4:
if block_lse.shape[1] == S and block_lse.shape[2] == H:
pass # Good
elif block_lse.shape[1] == H and block_lse.shape[2] == S:
block_lse = block_lse.transpose(1, 2)
elif block_lse.shape[1] == H and block_lse.shape[2] >= S: # Padding case
block_lse = block_lse[:, :, :S, :].transpose(1, 2)
# If shape is (B, H, S, 1) but expected (B, S, H, 1) because out is (B, S, H, D)
elif block_lse.shape[1] == H and block_lse.shape[2] == S and block_lse.shape[3] == 1:
block_lse = block_lse.transpose(1, 2)
# Case 1: block_lse is 3D (B, H, S) or (B, S, H) or (B, ?, ?)
elif block_lse.dim() == 3:
# Check for (B, H, S) - Standard SDPA/FA output
if block_lse.shape[1] == H and block_lse.shape[2] == S:
block_lse = block_lse.transpose(1, 2).unsqueeze(-1)
# Check for (B, S, H)
elif block_lse.shape[1] == S and block_lse.shape[2] == H:
block_lse = block_lse.unsqueeze(-1)
# Check for Padding: (B, H, S_pad) where S_pad >= S
elif block_lse.shape[1] == H and block_lse.shape[2] >= S:
# print(f"DEBUG: Trimming padding from lse. {block_lse.shape} -> S={S}")
block_lse = block_lse[:, :, :S].transpose(1, 2).unsqueeze(-1)
# Check for weird case: (B, S, H_pad) ? Unlikely for LSE but possible
elif block_lse.shape[1] == S and block_lse.shape[2] >= H:
block_lse = block_lse[:, :, :H].unsqueeze(-1)
# Check for flipped weird case: (B, S_pad, H)
elif block_lse.shape[1] >= S and block_lse.shape[2] == H:
block_lse = block_lse[:, :S, :].unsqueeze(-1)
# --- Shape Correction for lse (internal state) ---
# Ensure lse matches block_lse's corrected shape (B, S, H, 1)
if lse.shape != block_lse.shape:
# If lse was initialized with wrong shape, try to fix it
if lse.dim() == 4 and lse.shape[1] == block_lse.shape[2] and lse.shape[2] == block_lse.shape[1]:
lse = lse.transpose(1, 2)
elif lse.shape[1] >= S: # slice if lse was initialized with padding
lse = lse[:, :S, :, :]
# Final check
if lse.shape != block_lse.shape:
# Force broadcast if possible?
pass
try:
out = out - F.sigmoid(block_lse - lse) * (out - block_out)
lse = lse - F.logsigmoid(lse - block_lse)
except RuntimeError as e:
print(f"ERROR in _update_out_and_lse: {e}")
print(f"out: {out.shape}, lse: {lse.shape}")
print(f"block_out: {block_out.shape}, block_lse: {block_lse.shape}")
# raise e
raise e
return out, lse
def update_out_and_lse(
out: torch.Tensor | None,
lse: torch.Tensor | None,
block_out: torch.Tensor,
block_lse: torch.Tensor,
slice_=None,
) -> tuple[torch.Tensor, torch.Tensor]:
if out is None:
if slice_ is not None:
raise RuntimeError("first update_out_and_lse should not pass slice_ args")
out = block_out.to(torch.float32)
# Initialize LSE with robust logic (same as _update)
B, D1, D2, D3 = out.shape
S_guess = D1
H_guess = D2
if block_lse.dim() == 3:
if block_lse.shape[1] == H_guess and block_lse.shape[2] == S_guess:
lse = block_lse.transpose(1, 2).unsqueeze(-1)
elif block_lse.shape[1] == S_guess and block_lse.shape[2] == H_guess:
lse = block_lse.unsqueeze(-1)
elif block_lse.shape[1] == H_guess and block_lse.shape[2] >= S_guess: # Padding
lse = block_lse[:, :, :S_guess].transpose(1, 2).unsqueeze(-1)
elif block_lse.shape[1] == S_guess and block_lse.shape[2] >= H_guess: # Padding/Weird
lse = block_lse[:, :, :H_guess].unsqueeze(-1)
elif block_lse.shape[1] >= S_guess and block_lse.shape[2] == H_guess:
lse = block_lse[:, :S_guess, :].unsqueeze(-1)
# Reverse case: What if out is (B, H, S, D) so S=D2, H=D1?
elif block_lse.shape[1] == D1 and block_lse.shape[2] >= D2: # Matches (H, S)
# Then out is (B, H, S, D). We should transpose out!
out = out.transpose(1, 2)
lse = block_lse[:, :, :D2].transpose(1, 2).unsqueeze(-1) # (B, S, H, 1)
else:
# Fallback
lse = block_lse.transpose(-2, -1).unsqueeze(dim=-1)
else:
# Case 0: If block_lse is already 4D, check if it matches
if block_lse.dim() == 4:
if block_lse.shape[1] == S_guess and block_lse.shape[2] == H_guess:
lse = block_lse
elif block_lse.shape[1] == H_guess and block_lse.shape[2] == S_guess:
lse = block_lse.transpose(1, 2)
elif block_lse.shape[1] == H_guess and block_lse.shape[2] >= S_guess: # Padding case
lse = block_lse[:, :, :S_guess, :].transpose(1, 2)
elif block_lse.shape[1] == D1 and block_lse.shape[2] >= D2: # Matches (H, S)
# Then out is (B, H, S, D). We should transpose out!
out = out.transpose(1, 2)
lse = block_lse[:, :, :D2].transpose(1, 2) # (B, S, H, 1)
else:
lse = block_lse
else:
lse = block_lse
elif slice_ is not None:
slice_out, slice_lse = out[slice_], lse[slice_]
slice_out, slice_lse = _update_out_and_lse(slice_out, slice_lse, block_out, block_lse)
out[slice_], lse[slice_] = slice_out, slice_lse
else:
out, lse = _update_out_and_lse(out, lse, block_out, block_lse)
return out, lse
def flatten_varlen_lse(lse, cu_seqlens):
new_lse = []
for i in range(len(cu_seqlens) - 1):
start, end = cu_seqlens[i], cu_seqlens[i + 1]
new_lse.append(lse[i, :, : end - start])
return torch.cat(new_lse, dim=1)
def unflatten_varlen_lse(lse, cu_seqlens, max_seqlen: int):
num_seq = len(cu_seqlens) - 1
num_head = lse.shape[-2]
new_lse = torch.empty((num_seq, max_seqlen, num_head, 1), dtype=torch.float32, device=lse.device)
for i in range(num_seq):
start, end = cu_seqlens[i], cu_seqlens[i + 1]
new_lse[i, : end - start] = lse[start:end]
return new_lse.squeeze(dim=-1).transpose(1, 2).contiguous()