[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
@@ -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)
|
||||
Reference in new issue
Block a user