[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:
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()
|
||||
@@ -0,0 +1,302 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright (c) 2024, Jiarui Fang.
|
||||
# Adapted from https://github.com/feifeibear/long-context-attention
|
||||
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_selector import AttnType, select_flash_attn_impl
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_utils import update_out_and_lse
|
||||
from vllm_omni.diffusion.distributed.comm import RingComm
|
||||
|
||||
|
||||
def ring_flash_attn_forward(
|
||||
process_group,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
softmax_scale,
|
||||
dropout_p=0,
|
||||
causal=True,
|
||||
window_size=(-1, -1),
|
||||
softcap=0.0,
|
||||
alibi_slopes=None,
|
||||
deterministic=False,
|
||||
attn_type: AttnType = AttnType.FA,
|
||||
attn_processor=None,
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
):
|
||||
comm = RingComm(process_group)
|
||||
|
||||
out = None
|
||||
lse = None
|
||||
|
||||
next_k, next_v = None, None
|
||||
|
||||
# Check and adjust q, k, v to be contiguous
|
||||
if not q.is_contiguous():
|
||||
q = q.contiguous()
|
||||
if not k.is_contiguous():
|
||||
k = k.contiguous()
|
||||
if not v.is_contiguous():
|
||||
v = v.contiguous()
|
||||
|
||||
for step in range(comm.world_size):
|
||||
if step + 1 != comm.world_size:
|
||||
next_k: torch.Tensor
|
||||
next_v: torch.Tensor
|
||||
next_k = comm.send_recv(k)
|
||||
next_v = comm.send_recv(v)
|
||||
comm.commit()
|
||||
|
||||
if not causal or step <= comm.rank:
|
||||
step_k = k
|
||||
step_v = v
|
||||
if step == 0 and joint_tensor_key is not None:
|
||||
if joint_strategy == "front":
|
||||
step_k = torch.cat([joint_tensor_key, step_k], dim=1)
|
||||
step_v = torch.cat([joint_tensor_value, step_v], dim=1)
|
||||
else:
|
||||
step_k = torch.cat([step_k, joint_tensor_key], dim=1)
|
||||
step_v = torch.cat([step_v, joint_tensor_value], dim=1)
|
||||
|
||||
fn = select_flash_attn_impl(attn_type, stage="fwd-only", attn_processor=attn_processor)
|
||||
block_out, block_lse = fn(
|
||||
q,
|
||||
step_k,
|
||||
step_v,
|
||||
dropout_p=dropout_p,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal and step == 0,
|
||||
window_size=window_size,
|
||||
softcap=softcap,
|
||||
alibi_slopes=alibi_slopes,
|
||||
return_softmax=True and dropout_p > 0,
|
||||
)
|
||||
|
||||
# Ensure block_out is contiguous if needed, though usually it is from FA
|
||||
|
||||
if attn_type == AttnType.SPARSE_SAGE:
|
||||
out, lse = block_out, block_lse
|
||||
else:
|
||||
out, lse = update_out_and_lse(out, lse, block_out, block_lse)
|
||||
|
||||
if step + 1 != comm.world_size:
|
||||
comm.wait()
|
||||
k = next_k
|
||||
v = next_v
|
||||
|
||||
out = out.to(q.dtype)
|
||||
if attn_type != AttnType.SPARSE_SAGE:
|
||||
lse = lse.squeeze(dim=-1).transpose(1, 2)
|
||||
return out, lse
|
||||
|
||||
|
||||
class RingFlashAttnFunc(torch.autograd.Function):
|
||||
"""Ring Flash Attention autograd function (inference only, no backward)."""
|
||||
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
dropout_p,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size,
|
||||
softcap,
|
||||
alibi_slopes,
|
||||
deterministic,
|
||||
return_softmax,
|
||||
group,
|
||||
attn_type,
|
||||
attn_processor,
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
):
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** (-0.5)
|
||||
|
||||
assert alibi_slopes is None
|
||||
q = q.contiguous()
|
||||
k = k.contiguous()
|
||||
v = v.contiguous()
|
||||
|
||||
out, softmax_lse = ring_flash_attn_forward(
|
||||
group,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
softmax_scale=softmax_scale,
|
||||
dropout_p=dropout_p,
|
||||
causal=causal,
|
||||
window_size=window_size,
|
||||
softcap=softcap,
|
||||
alibi_slopes=alibi_slopes,
|
||||
deterministic=False,
|
||||
attn_type=attn_type,
|
||||
attn_processor=attn_processor,
|
||||
joint_tensor_key=joint_tensor_key,
|
||||
joint_tensor_value=joint_tensor_value,
|
||||
joint_strategy=joint_strategy,
|
||||
)
|
||||
return out if not return_softmax else (out, softmax_lse, None)
|
||||
|
||||
|
||||
def ring_flash_attn_qkvpacked_func(
|
||||
qkv,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=False,
|
||||
window_size=(-1, -1),
|
||||
softcap=0.0,
|
||||
alibi_slopes=None,
|
||||
deterministic=False,
|
||||
return_attn_probs=False,
|
||||
group=None,
|
||||
attn_type: AttnType = AttnType.FA,
|
||||
):
|
||||
return RingFlashAttnFunc.apply(
|
||||
qkv[:, :, 0],
|
||||
qkv[:, :, 1],
|
||||
qkv[:, :, 2],
|
||||
dropout_p,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size,
|
||||
softcap,
|
||||
alibi_slopes,
|
||||
deterministic,
|
||||
return_attn_probs,
|
||||
group,
|
||||
attn_type,
|
||||
None, # attn_processor
|
||||
None, # joint_tensor_key
|
||||
None, # joint_tensor_value
|
||||
"front", # joint_strategy
|
||||
)
|
||||
|
||||
|
||||
def ring_flash_attn_kvpacked_func(
|
||||
q,
|
||||
kv,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=False,
|
||||
window_size=(-1, -1),
|
||||
softcap=0.0,
|
||||
alibi_slopes=None,
|
||||
deterministic=False,
|
||||
return_attn_probs=False,
|
||||
group=None,
|
||||
attn_type: AttnType = AttnType.FA,
|
||||
):
|
||||
return RingFlashAttnFunc.apply(
|
||||
q,
|
||||
kv[:, :, 0],
|
||||
kv[:, :, 1],
|
||||
dropout_p,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size,
|
||||
softcap,
|
||||
alibi_slopes,
|
||||
deterministic,
|
||||
return_attn_probs,
|
||||
group,
|
||||
attn_type,
|
||||
None, # attn_processor
|
||||
None, # joint_tensor_key
|
||||
None, # joint_tensor_value
|
||||
"front", # joint_strategy
|
||||
)
|
||||
|
||||
|
||||
def ring_flash_attn_func(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=False,
|
||||
window_size=(-1, -1),
|
||||
softcap=0.0,
|
||||
alibi_slopes=None,
|
||||
deterministic=False,
|
||||
return_attn_probs=False,
|
||||
group=None,
|
||||
attn_type: AttnType = AttnType.FA,
|
||||
attn_processor=None,
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor, None]:
|
||||
"""Ring Attention forward pass using Flash Attention backend.
|
||||
|
||||
Implements Ring Attention with sequence parallelism using a ring-based P2P
|
||||
communication pattern. The sequence dimension is sharded across devices, and
|
||||
Key/Value blocks are circulated through the ring to accumulate attention results.
|
||||
|
||||
Args:
|
||||
q (torch.Tensor): Query tensor of shape (batch, seq_len, num_heads, head_dim).
|
||||
Sequence dimension is sharded across the ring group.
|
||||
k (torch.Tensor): Key tensor of shape (batch, seq_len, num_heads, head_dim).
|
||||
Sequence dimension is sharded across the ring group.
|
||||
v (torch.Tensor): Value tensor of shape (batch, seq_len, num_heads, head_dim).
|
||||
Sequence dimension is sharded across the ring group.
|
||||
dropout_p (float): Dropout probability. Defaults to 0.0.
|
||||
softmax_scale (float | None): Scaling factor for softmax.
|
||||
If None, computed as head_dim^(-0.5).
|
||||
causal (bool): Whether to apply causal masking. Defaults to False.
|
||||
window_size (tuple[int, int]): Sliding window size for attention.
|
||||
(-1, -1) means no windowing.
|
||||
softcap (float): Soft capping value for attention logits. Defaults to 0.0.
|
||||
alibi_slopes (torch.Tensor | None): ALiBi slopes for positional bias.
|
||||
Not supported.
|
||||
deterministic (bool): Whether to use deterministic algorithms.
|
||||
Defaults to False.
|
||||
return_attn_probs (bool): If True, returns (out, softmax_lse, None).
|
||||
Defaults to False.
|
||||
group (ProcessGroup | None): Process group for ring communication.
|
||||
Defaults to None.
|
||||
attn_type (AttnType): Flash Attention implementation type
|
||||
(AttnType.FA, AttnType.FA3, etc.).
|
||||
attn_processor (Callable | None): Custom attention processor for sparse
|
||||
attention. Defaults to None.
|
||||
joint_tensor_key (torch.Tensor | None): Additional key tensor for joint
|
||||
attention (e.g., text + image). Concatenated only at step=0.
|
||||
Defaults to None.
|
||||
joint_tensor_value (torch.Tensor | None): Additional value tensor for
|
||||
joint attention (e.g., text + image). Concatenated only at step=0.
|
||||
Defaults to None.
|
||||
joint_strategy (str): Concatenation strategy ("front" or "back").
|
||||
Defaults to "front".
|
||||
|
||||
Returns:
|
||||
Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor, None]]:
|
||||
- If return_attn_probs is False: Output tensor (batch, seq_len, num_heads, head_dim).
|
||||
- If return_attn_probs is True: A tuple (out, softmax_lse, None).
|
||||
"""
|
||||
return RingFlashAttnFunc.apply(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
dropout_p,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size,
|
||||
softcap,
|
||||
alibi_slopes,
|
||||
deterministic,
|
||||
return_attn_probs,
|
||||
group,
|
||||
attn_type,
|
||||
attn_processor,
|
||||
joint_tensor_key,
|
||||
joint_tensor_value,
|
||||
joint_strategy,
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright (c) 2024, Jiarui Fang.
|
||||
# Adapted from https://github.com/feifeibear/long-context-attention
|
||||
|
||||
# adapted from https://github.com/huggingface/picotron/blob/main/picotron/context_parallel/context_parallel.py
|
||||
# Copyright 2024 The HuggingFace Inc. team and Jiarui Fang.
|
||||
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_kernels import pytorch_attn_forward
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_utils import update_out_and_lse
|
||||
from vllm_omni.diffusion.distributed.comm import RingComm
|
||||
|
||||
|
||||
def ring_pytorch_attn_func(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=False,
|
||||
window_size=(-1, -1),
|
||||
softcap=0.0,
|
||||
alibi_slopes=None,
|
||||
deterministic=False,
|
||||
return_attn_probs=False,
|
||||
group=None,
|
||||
op_type="efficient",
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
):
|
||||
return RingAttentionFunc.apply(
|
||||
group,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
softmax_scale,
|
||||
causal,
|
||||
op_type,
|
||||
joint_tensor_key,
|
||||
joint_tensor_value,
|
||||
joint_strategy,
|
||||
)
|
||||
|
||||
|
||||
class RingAttentionFunc(torch.autograd.Function):
|
||||
"""Ring Attention autograd function using PyTorch SDPA (inference only, no backward)."""
|
||||
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
group,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
sm_scale,
|
||||
is_causal,
|
||||
op_type,
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
):
|
||||
comm = RingComm(group)
|
||||
# Ensure tensors are contiguous for P2P communication
|
||||
q = q.contiguous()
|
||||
k = k.contiguous()
|
||||
v = v.contiguous()
|
||||
|
||||
out, lse = None, None
|
||||
next_k, next_v = None, None
|
||||
|
||||
if sm_scale is None:
|
||||
sm_scale = q.shape[-1] ** -0.5
|
||||
|
||||
for step in range(comm.world_size):
|
||||
if step + 1 != comm.world_size:
|
||||
next_k = comm.send_recv(k)
|
||||
next_v = comm.send_recv(v)
|
||||
comm.commit()
|
||||
|
||||
if not is_causal or step <= comm.rank:
|
||||
step_k = k
|
||||
step_v = v
|
||||
if step == 0 and joint_tensor_key is not None:
|
||||
if joint_strategy == "front":
|
||||
step_k = torch.cat([joint_tensor_key, step_k], dim=1)
|
||||
step_v = torch.cat([joint_tensor_value, step_v], dim=1)
|
||||
else:
|
||||
step_k = torch.cat([step_k, joint_tensor_key], dim=1)
|
||||
step_v = torch.cat([step_v, joint_tensor_value], dim=1)
|
||||
|
||||
block_out, block_lse = pytorch_attn_forward(
|
||||
q,
|
||||
step_k,
|
||||
step_v,
|
||||
softmax_scale=sm_scale,
|
||||
causal=is_causal and step == 0,
|
||||
op_type=op_type,
|
||||
)
|
||||
out, lse = update_out_and_lse(out, lse, block_out, block_lse)
|
||||
|
||||
if step + 1 != comm.world_size:
|
||||
comm.wait()
|
||||
k = next_k
|
||||
v = next_v
|
||||
|
||||
out = out.to(q.dtype)
|
||||
|
||||
return out
|
||||
Reference in new issue
Block a user