[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()
@@ -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
+84 -11
View File
@@ -6,12 +6,20 @@
# Adapted from
# https://github.com/feifeibear/long-context-attention/blob/main/yunchang/attention/layer.py
import torch
import torch.nn as nn
from vllm.logger import init_logger
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.parallel import build_parallel_attention_strategy
from vllm_omni.diffusion.attention.parallel.ring import RingParallelAttention
from vllm_omni.diffusion.attention.selector import get_attn_backend
from vllm_omni.diffusion.data import get_current_omni_diffusion_config
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
from vllm_omni.utils.platform_utils import is_npu
logger = init_logger(__name__)
class Attention(nn.Module):
@@ -43,9 +51,28 @@ class Attention(nn.Module):
self.scatter_idx = scatter_idx
self.gather_idx = gather_idx
self.use_sync = use_sync
# Parallel attention (communication / resharding) is a pluggable strategy.
# This keeps the attention kernel backend selection orthogonal.
self.parallel = build_parallel_attention_strategy(
self.causal = causal
self.use_ring = False
self.ring_pg = None
self.ring_runner = None
try:
config = get_current_omni_diffusion_config()
if config.parallel_config.ring_degree > 1:
self.use_ring = True
try:
sp_group = get_sp_group()
self.ring_pg = sp_group.ring_group
self.ring_runner = RingParallelAttention(sp_group)
except Exception:
self.use_ring = False
self.ring_runner = None
except Exception:
self.use_ring = False
self.ring_runner = None
self.parallel_strategy = build_parallel_attention_strategy(
scatter_idx=scatter_idx,
gather_idx=gather_idx,
use_sync=use_sync,
@@ -58,13 +85,59 @@ class Attention(nn.Module):
value: torch.Tensor,
attn_metadata: AttentionMetadata = None,
) -> torch.Tensor:
# Parallel strategy may reshard/communicate QKV before the attention kernel.
query, key, value, attn_metadata, ctx = self.parallel.pre_attention(query, key, value, attn_metadata)
# 1. Prepare inputs (Communication / Resharding)
# For Ulysses: AllToAll Q/K/V; Slicing joint_q/k/v
# For Ring: Concat joint_q
query, key, value, attn_metadata, ctx = self.parallel_strategy.pre_attention(query, key, value, attn_metadata)
# shape: (batch_size, seq_len, num_heads, head_size)
attn_output = self.attention.forward(query, key, value, attn_metadata)
if isinstance(attn_output, tuple):
attn_output = attn_output[0]
# 2. Kernel Execution (Computation)
if self.use_ring:
out = self._run_ring_attention(query, key, value, attn_metadata)
else:
out = self._run_local_attention(query, key, value, attn_metadata)
# Parallel strategy may need to reverse resharding after the kernel.
return self.parallel.post_attention(attn_output, ctx)
# 3. Post-processing (Reverse Communication)
# For Ulysses: AllToAll Output, and AllGather Joint Output
out = self.parallel_strategy.post_attention(out, ctx)
return out
def _run_local_attention(self, query, key, value, attn_metadata):
# Check backend preference from config
try:
config = get_current_omni_diffusion_config()
backend_pref = config.attention_backend
except Exception:
backend_pref = None
if backend_pref == "flash_attn" and query.dtype == torch.float32:
logger.warning(
"Flash Attention does not support float32. Overriding user config "
f"attention_backend='{backend_pref}' to 'sdpa' for dtype={query.dtype}."
)
backend_pref = "sdpa"
if is_npu():
return self.attention(
query,
key,
value,
num_heads=query.shape[-2],
input_layout="BSND",
scale=self.softmax_scale,
softmax_lse_flag=True,
pre_tokens=65535,
next_tokens=65535,
)[0]
# Fallback to standard attention
return self.attention.forward(query, key, value, attn_metadata)
def _run_ring_attention(self, query, key, value, attn_metadata):
# Delegate to RingParallelAttention strategy if available
if self.ring_runner is not None:
return self.ring_runner.run_attention(
query, key, value, attn_metadata, softmax_scale=self.softmax_scale, causal=self.causal
)
raise RuntimeError("Ring attention is enabled but strategy is not RingParallelAttention")
@@ -4,9 +4,10 @@
from __future__ import annotations
from vllm_omni.diffusion.attention.parallel.base import NoParallelAttention, ParallelAttentionStrategy
from vllm_omni.diffusion.attention.parallel.ring import RingParallelAttention
from vllm_omni.diffusion.attention.parallel.ulysses import UlyssesParallelAttention
from vllm_omni.diffusion.data import get_current_omni_diffusion_config
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
from vllm_omni.diffusion.distributed.parallel_state import get_sequence_parallel_world_size, get_sp_group
def build_parallel_attention_strategy(
@@ -28,13 +29,19 @@ def build_parallel_attention_strategy(
except Exception:
return NoParallelAttention()
# Current implementation supports Ulysses sequence-parallel attention.
# We intentionally do NOT infer ring attention from ring_degree here yet.
if getattr(p, "ulysses_degree", 1) > 1:
try:
sp_group = get_sp_group()
except Exception:
ulysses_degree = getattr(p, "ulysses_degree", 1)
ring_degree = getattr(p, "ring_degree", 1)
try:
sp_group = get_sp_group()
# Ensure SP group is initialized and world size > 1
if get_sequence_parallel_world_size() <= 1:
return NoParallelAttention()
except Exception:
return NoParallelAttention()
# Ulysses (or Hybrid Ulysses+Ring)
if ulysses_degree > 1:
return UlyssesParallelAttention(
sp_group=sp_group,
scatter_idx=scatter_idx,
@@ -42,4 +49,10 @@ def build_parallel_attention_strategy(
use_sync=use_sync,
)
# Pure Ring Attention
if ring_degree > 1:
return RingParallelAttention(
sp_group=sp_group,
)
return NoParallelAttention()
@@ -0,0 +1,170 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
import torch
from vllm.logger import init_logger
# import torch.distributed as dist # Not used directly here, but good practice if needed
from vllm_omni.diffusion.attention.backends.ring.ring_globals import HAS_FLASH_ATTN
from vllm_omni.diffusion.attention.backends.ring.ring_selector import AttnType
from vllm_omni.diffusion.attention.parallel.base import (
ParallelAttentionContext,
# ParallelAttentionStrategy, # Not used in type hint below currently
)
# from vllm_omni.diffusion.attention.backends.ring_selector import AttnType # Already imported above
from vllm_omni.diffusion.data import get_current_omni_diffusion_config
from vllm_omni.diffusion.distributed.group_coordinator import SequenceParallelGroupCoordinator
if TYPE_CHECKING:
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
@dataclass(frozen=True, slots=True)
class _RingCtx(ParallelAttentionContext):
"""Per-forward context for Ring sequence-parallel attention."""
# Ring attention typically doesn't need complex context for post-processing
# as the output is already correctly sharded along sequence dimension.
pass
class RingParallelAttention:
"""Ring sequence-parallel strategy.
This strategy prepares inputs for Ring Attention.
Key responsibilities:
- Concatenate joint_query (Text) to query (Image) if present.
- Keep joint_key/value separate in metadata for the Ring kernel to handle as static prefix.
"""
def __init__(
self,
sp_group: SequenceParallelGroupCoordinator,
attn_backend_pref: str | None = None,
) -> None:
self._sp_group = sp_group
self.attn_backend_pref = attn_backend_pref
@property
def enabled(self) -> bool:
return True
@property
def name(self) -> str:
return "ring"
def pre_attention(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None,
):
joint_tensor_query = None
joint_strategy = "front"
if attn_metadata is not None:
joint_tensor_query = attn_metadata.joint_query
joint_strategy = attn_metadata.joint_strategy
if joint_tensor_query is not None:
supported_joint_strategy = ["front", "rear"]
if joint_strategy not in supported_joint_strategy:
raise ValueError(f"joint_strategy: {joint_strategy} not supported.")
if joint_strategy == "front":
query = torch.cat([joint_tensor_query, query], dim=1)
else:
query = torch.cat([query, joint_tensor_query], dim=1)
# Note: We do NOT concatenate joint_key/value here.
# They are preserved in attn_metadata and will be passed
# explicitly to ring_flash_attn_func.
ctx = _RingCtx(name=self.name)
return query, key, value, attn_metadata, ctx
def post_attention(self, attn_output: torch.Tensor, ctx: ParallelAttentionContext | None) -> torch.Tensor:
# Ring attention output is already sharded correctly along sequence dimension.
return attn_output
def run_attention(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None,
softmax_scale: float | None = None,
causal: bool = False,
) -> torch.Tensor:
"""Run the actual Ring Attention kernel."""
if softmax_scale is None:
softmax_scale = query.shape[-1] ** -0.5
backend_pref = self.attn_backend_pref
if backend_pref is None:
try:
config = get_current_omni_diffusion_config()
# config might not have attention_backend attribute if not updated
backend_pref = getattr(config, "attention_backend", None)
except Exception:
backend_pref = None
# Fallback for FP32 or if Flash Attention is not available
if query.dtype == torch.float32 or not HAS_FLASH_ATTN:
if not HAS_FLASH_ATTN and backend_pref != "sdpa":
logger = init_logger(__name__)
logger.warning("Flash Attention is not available! Force enabling SDPA.")
backend_pref = "sdpa"
# Extract joint tensors
joint_key, joint_value = None, None
joint_strategy = "front"
if attn_metadata is not None:
joint_key = attn_metadata.joint_key
joint_value = attn_metadata.joint_value
if attn_metadata.joint_strategy is not None:
joint_strategy = attn_metadata.joint_strategy
if backend_pref == "sdpa" or backend_pref == "torch":
from vllm_omni.diffusion.attention.backends.ring_pytorch_attn import ring_pytorch_attn_func
return ring_pytorch_attn_func(
query,
key,
value,
softmax_scale=softmax_scale,
causal=causal,
group=self._sp_group.ring_group,
op_type="efficient",
joint_tensor_key=joint_key,
joint_tensor_value=joint_value,
joint_strategy=joint_strategy,
)
from vllm_omni.diffusion.attention.backends.ring_flash_attn import ring_flash_attn_func
return ring_flash_attn_func(
query,
key,
value,
dropout_p=0.0,
softmax_scale=softmax_scale,
causal=causal,
window_size=(-1, -1),
softcap=0.0,
alibi_slopes=None,
deterministic=False,
# return_attn_probs=False, # Removed as it might not be supported in signature
group=self._sp_group.ring_group,
attn_type=AttnType.FA,
joint_tensor_key=joint_key,
joint_tensor_value=joint_value,
joint_strategy=joint_strategy,
)
@@ -22,6 +22,8 @@ class _UlyssesCtx(ParallelAttentionContext):
scatter_idx: int
gather_idx: int
use_sync: bool
joint_len: int = 0
joint_strategy: str = "front"
class UlyssesParallelAttention:
@@ -29,8 +31,8 @@ class UlyssesParallelAttention:
This preserves the semantics previously implemented in
`Attention._forward_ulysses`:
- If `AttentionMetadata.joint_*` is provided, joint_query is concatenated to
query *before* all-to-all; joint_key/value are concatenated *after* all-to-all.
- If `AttentionMetadata.joint_*` is provided, joint_query/key/value are
concatenated *after* all-to-all.
- joint_key/value are assumed to be replicated across SP ranks and are sliced
by ulysses head rank before concatenation.
"""
@@ -64,7 +66,8 @@ class UlyssesParallelAttention:
attn_metadata: AttentionMetadata | None,
):
joint_tensor_query = joint_tensor_key = joint_tensor_value = None
joint_strategy = None
joint_strategy = "front"
joint_len = 0
if attn_metadata is not None:
joint_tensor_query = attn_metadata.joint_query
@@ -80,10 +83,22 @@ class UlyssesParallelAttention:
f"joint_strategy: {joint_strategy} not supported."
f" supported joint strategy: {supported_joint_strategy}"
)
if joint_strategy == "rear":
query = torch.cat([query, joint_tensor_query], dim=1)
else:
query = torch.cat([joint_tensor_query, query], dim=1)
# Slice joint_query for this Ulysses rank
# joint_query is (B, S, H, D). We split H (dim 2).
ulysses_world_size = self._sp_group.ulysses_world_size
ulysses_rank = self._sp_group.ulysses_rank
attn_heads_per_ulysses_rank = joint_tensor_query.shape[-2] // ulysses_world_size
# Note: We use the same heads for Q/K/V
joint_tensor_query = joint_tensor_query[
...,
attn_heads_per_ulysses_rank * ulysses_rank : attn_heads_per_ulysses_rank * (ulysses_rank + 1),
:,
]
joint_len = joint_tensor_query.shape[1]
is_joint = True
elif joint_tensor_query is None and joint_tensor_key is None and joint_tensor_value is None:
pass
@@ -92,27 +107,46 @@ class UlyssesParallelAttention:
if is_joint:
# Slice joint key/value heads for this ulysses rank.
ulysses_world_size = self._sp_group.ulysses_world_size
ulysses_rank = self._sp_group.ulysses_rank
attn_heads_per_ulysses_rank = joint_tensor_key.shape[-2] // ulysses_world_size
# Using same slicing logic as query
attn_heads_per_ulysses_rank_kv = joint_tensor_key.shape[-2] // ulysses_world_size
joint_tensor_key = joint_tensor_key[
...,
attn_heads_per_ulysses_rank * ulysses_rank : attn_heads_per_ulysses_rank * (ulysses_rank + 1),
attn_heads_per_ulysses_rank_kv * ulysses_rank : attn_heads_per_ulysses_rank_kv * (ulysses_rank + 1),
:,
]
joint_tensor_value = joint_tensor_value[
...,
attn_heads_per_ulysses_rank * ulysses_rank : attn_heads_per_ulysses_rank * (ulysses_rank + 1),
attn_heads_per_ulysses_rank_kv * ulysses_rank : attn_heads_per_ulysses_rank_kv * (ulysses_rank + 1),
:,
]
# Update metadata with sliced tensors so Ring attention can use them if needed
if attn_metadata is not None:
attn_metadata.joint_key = joint_tensor_key
attn_metadata.joint_value = joint_tensor_value
# (bs, seq_len/P, head_cnt, head_size) -> (bs, seq_len, head_cnt/P, head_size)
query = SeqAllToAll4D.apply(self._ulysses_pg, query, self._scatter_idx, self._gather_idx, self._use_sync)
key = SeqAllToAll4D.apply(self._ulysses_pg, key, self._scatter_idx, self._gather_idx, self._use_sync)
value = SeqAllToAll4D.apply(self._ulysses_pg, value, self._scatter_idx, self._gather_idx, self._use_sync)
if is_joint:
# Concatenate joint key/value after all-to-all (matches previous implementation).
# Concatenate joint query AFTER AllToAll
# Image query is now (B, S, H/P, D). Joint query is (B, S_txt, H/P, D).
# This is dimensionally consistent.
if joint_strategy == "rear":
query = torch.cat([query, joint_tensor_query], dim=1)
else:
query = torch.cat([joint_tensor_query, query], dim=1)
# Check if Ring Attention is also active (Hybrid mode)
# If Ring is active, we should NOT concatenate joint_key/value to k/v here.
# Instead, they should remain in attn_metadata and be passed to the Ring kernel.
use_ring = self._sp_group.ring_world_size > 1
if is_joint and not use_ring:
# Concatenate joint key/value after all-to-all ONLY for pure Ulysses (Local Attention).
if joint_strategy == "front":
key = torch.cat([joint_tensor_key, key], dim=1)
value = torch.cat([joint_tensor_value, value], dim=1)
@@ -126,10 +160,47 @@ class UlyssesParallelAttention:
scatter_idx=self._scatter_idx,
gather_idx=self._gather_idx,
use_sync=self._use_sync,
joint_len=joint_len,
joint_strategy=joint_strategy,
)
return query, key, value, attn_metadata, ctx
def post_attention(self, attn_output: torch.Tensor, ctx: ParallelAttentionContext | None) -> torch.Tensor:
assert isinstance(ctx, _UlyssesCtx), f"Unexpected ctx type: {type(ctx)!r}"
# Reverse: (bs, seq_len, head_cnt/P, head_size) -> (bs, seq_len/P, head_cnt, head_size)
# If we have joint tensors (Text), they were Head-Sliced.
# The main sequence (Image) was Sequence-Sliced.
# attn_output contains [Joint_Sliced | Image_Sliced] (if strategy='front').
if ctx.joint_len > 0:
joint_len = ctx.joint_len
if ctx.joint_strategy == "front":
output_joint = attn_output[:, :joint_len]
output_img = attn_output[:, joint_len:]
else:
output_img = attn_output[:, :-joint_len]
output_joint = attn_output[:, -joint_len:]
# 1. Process Image part: Standard Ulysses Reverse (AllToAll)
# (bs, seq_len, head_cnt/P, head_size) -> (bs, seq_len/P, head_cnt, head_size)
# SeqAllToAll4D handles: Scatter gather_idx, Gather scatter_idx.
# Forward: Scatter 2 (H), Gather 1 (S).
# Reverse: Scatter 1 (S), Gather 2 (H).
output_img = SeqAllToAll4D.apply(ctx.ulysses_pg, output_img, ctx.gather_idx, ctx.scatter_idx, ctx.use_sync)
# 2. Process Joint part: AllGather on Heads
# Input: (B, JointLen, H/P, D). Output: (B, JointLen, H, D).
# AllGather along dim 2.
gathered_joint = [torch.zeros_like(output_joint) for _ in range(dist.get_world_size(ctx.ulysses_pg))]
dist.all_gather(gathered_joint, output_joint, group=ctx.ulysses_pg)
output_joint = torch.cat(gathered_joint, dim=2)
# 3. Recombine
if ctx.joint_strategy == "front":
return torch.cat([output_joint, output_img], dim=1)
else:
return torch.cat([output_img, output_joint], dim=1)
# Standard Ulysses Reverse
return SeqAllToAll4D.apply(ctx.ulysses_pg, attn_output, ctx.gather_idx, ctx.scatter_idx, ctx.use_sync)
+1 -1
View File
@@ -245,7 +245,7 @@ class OmniDiffusionConfig:
tf_model_config: TransformerConfig = field(default_factory=TransformerConfig)
# Attention
# attention_backend: str = None
attention_backend: str | None = None
# Running mode
# mode: ExecutionMode = ExecutionMode.INFERENCE
+53
View File
@@ -8,6 +8,8 @@ import torch
import torch.distributed as dist
from torch import Tensor
__all__ = ["all_to_all_4D", "all_to_all_5D", "SeqAllToAll4D", "SeqAllToAll5D", "RingComm"]
def all_to_all_4D(
input: torch.tensor, scatter_idx: int = 2, gather_idx: int = 1, group=None, use_sync: bool = False
@@ -219,3 +221,54 @@ class SeqAllToAll5D(torch.autograd.Function):
ctx.use_sync = use_sync
return all_to_all_5D(input, scatter_idx, gather_idx, group=group, use_sync=use_sync)
class RingComm:
"""Ring communication utility for Ring Attention P2P communication."""
def __init__(self, process_group: dist.ProcessGroup):
self._process_group = process_group
self._ops = []
self.rank = dist.get_rank(self._process_group)
self.world_size = dist.get_world_size(self._process_group)
self._reqs = None
self.send_rank = (self.rank + 1) % self.world_size
self.recv_rank = (self.rank - 1) % self.world_size
if process_group is not None:
self.send_rank = dist.get_global_rank(self._process_group, self.send_rank)
self.recv_rank = dist.get_global_rank(self._process_group, self.recv_rank)
def send_recv(self, to_send: torch.Tensor, recv_tensor: torch.Tensor | None = None) -> torch.Tensor:
# Ensure to_send is contiguous for P2P
if not to_send.is_contiguous():
to_send = to_send.contiguous()
if recv_tensor is None:
# Create a contiguous buffer for receiving
res = torch.empty_like(to_send, memory_format=torch.contiguous_format)
# print(f"send_recv: empty_like {to_send.shape}")
else:
res = recv_tensor
if not res.is_contiguous():
res = res.contiguous()
send_op = dist.P2POp(dist.isend, to_send, self.send_rank, group=self._process_group)
recv_op = dist.P2POp(dist.irecv, res, self.recv_rank, group=self._process_group)
self._ops.append(send_op)
self._ops.append(recv_op)
return res
def commit(self):
if self._reqs is not None:
raise RuntimeError("commit called twice")
self._reqs = dist.batch_isend_irecv(self._ops)
def wait(self):
if self._reqs is None:
raise RuntimeError("wait called before commit")
for req in self._reqs:
req.wait()
self._reqs = None
self._ops = []