[Diffusion] Add native paged KV backend for diffusion workers (#6102)
Signed-off-by: Acerak01-fy <wfy2003324@163.com> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
1 parent
c2daa471c3
commit
72ee535fcd
34 files changed
+4595
-71
No files matched your search
@@ -15,6 +15,11 @@ class AttentionBackend(ABC):
|
||||
|
||||
accept_output_buffer: bool = False
|
||||
supports_piecewise_spans: bool = False
|
||||
# A backend that supports this capability can consume the opaque paged-KV
|
||||
# context prepared by the diffusion Worker data plane. Keeping the
|
||||
# capability on the backend class prevents a paged request from silently
|
||||
# falling back to dense attention on an incompatible implementation.
|
||||
supports_paged_kv: bool = False
|
||||
# The backend can represent a contiguous valid K/V prefix by slicing the
|
||||
# tensors instead of materializing a padding mask. Models may use this to
|
||||
# avoid a slower masked-attention plan when tail padding is not semantic.
|
||||
@@ -221,6 +226,18 @@ class AttentionImpl(ABC, Generic[T]):
|
||||
else:
|
||||
raise NotImplementedError(f"No forward implementation for platform: {current_omni_platform}")
|
||||
|
||||
def forward_paged(self, paged_kv_context: Any) -> torch.Tensor:
|
||||
"""Execute one Worker-prepared paged-KV attention call.
|
||||
|
||||
The context is intentionally opaque to the common attention layer.
|
||||
Backends opt in by setting ``supports_paged_kv`` on their backend
|
||||
class and implementing this method. Dense callers continue to use
|
||||
``forward`` unchanged.
|
||||
"""
|
||||
|
||||
del paged_kv_context
|
||||
raise NotImplementedError(f"{type(self).__name__} does not support paged KV attention")
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
|
||||
@@ -15,6 +15,7 @@ from vllm_omni.diffusion.attention.backends.abstract import (
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import _maybe_reshape_attn_mask
|
||||
from vllm_omni.diffusion.attention.backends.utils.piecewise_attn import (
|
||||
piecewise_attn,
|
||||
run_paged_piecewise_plan,
|
||||
)
|
||||
from vllm_omni.diffusion.config import get_current_diffusion_config_or_none
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -25,6 +26,7 @@ logger = init_logger(__name__)
|
||||
class FlashAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
supports_piecewise_spans: bool = True
|
||||
supports_paged_kv: bool = True
|
||||
|
||||
@classmethod
|
||||
def supports_packed_mask_free(cls) -> bool:
|
||||
@@ -246,6 +248,73 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
# (b s) h d -> b s h d
|
||||
return out.reshape(batch_size, q_len, *out.shape[1:])
|
||||
|
||||
def forward_paged(self, paged_kv_context) -> torch.Tensor:
|
||||
"""Run platform-native paged attention through the Omni backend.
|
||||
|
||||
``DiffusionPagedAttentionAdapter`` owns BlockTables and prepares the
|
||||
rank-local native cache context. The adapter no longer performs the
|
||||
attention call itself; this method is the backend-owned execution
|
||||
boundary. Its native layer wrapper keeps vLLM version-specific cache
|
||||
and kernel details out of Omni's common ``Attention`` layer.
|
||||
"""
|
||||
|
||||
layer = getattr(paged_kv_context, "layer", None)
|
||||
if layer is None:
|
||||
raise TypeError("paged_kv_context must expose a native diffusion attention layer")
|
||||
kv_cache = getattr(layer, "kv_cache", None)
|
||||
if kv_cache is None:
|
||||
raise RuntimeError(f"Native KV cache is not bound for diffusion layer {layer.layer_name!r}")
|
||||
native_impl = getattr(layer, "impl", None)
|
||||
if native_impl is None:
|
||||
raise RuntimeError(f"Native attention implementation is not bound for diffusion layer {layer.layer_name!r}")
|
||||
if not layer.attn_backend.forward_includes_kv_cache_update:
|
||||
native_impl.do_kv_cache_update(
|
||||
layer,
|
||||
paged_kv_context.key_write,
|
||||
paged_kv_context.value_write,
|
||||
kv_cache,
|
||||
paged_kv_context.slot_mapping,
|
||||
)
|
||||
|
||||
def run_native_attention(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
native_metadata,
|
||||
) -> torch.Tensor:
|
||||
output = torch.empty(
|
||||
(query.shape[0], layer.num_heads, layer.head_size_v),
|
||||
dtype=query.dtype,
|
||||
device=query.device,
|
||||
)
|
||||
return native_impl.forward(
|
||||
layer,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
kv_cache,
|
||||
native_metadata,
|
||||
output,
|
||||
)
|
||||
|
||||
if paged_kv_context.piecewise_plan is not None:
|
||||
output = run_paged_piecewise_plan(
|
||||
paged_kv_context.query,
|
||||
paged_kv_context.key_write,
|
||||
paged_kv_context.value_write,
|
||||
paged_kv_context.piecewise_plan,
|
||||
paged_kv_context.piecewise_native_metadata,
|
||||
run_native_attention,
|
||||
)
|
||||
else:
|
||||
output = run_native_attention(
|
||||
paged_kv_context.query,
|
||||
paged_kv_context.key_write,
|
||||
paged_kv_context.value_write,
|
||||
paged_kv_context.native_metadata,
|
||||
)
|
||||
return paged_kv_context.restore_output(output)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
|
||||
@@ -15,6 +15,8 @@ Per segment:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Literal, NamedTuple
|
||||
|
||||
import torch
|
||||
@@ -123,3 +125,109 @@ def piecewise_attn(
|
||||
if len(outputs) == 1:
|
||||
return outputs[0]
|
||||
return torch.cat(outputs, dim=1)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PagedPiecewiseSegment:
|
||||
"""One aligned segment across rows in a packed paged batch."""
|
||||
|
||||
row_segments: tuple[Segment, ...]
|
||||
query_indices: torch.Tensor
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PagedPiecewisePlan:
|
||||
"""Piecewise segment batches for one packed paged-attention batch."""
|
||||
|
||||
spans: tuple[tuple[tuple[int, int], ...], ...]
|
||||
segments: tuple[PagedPiecewiseSegment, ...]
|
||||
num_query_tokens: int
|
||||
|
||||
|
||||
PagedPiecewiseRunner = Callable[
|
||||
[torch.Tensor, torch.Tensor, torch.Tensor, object],
|
||||
torch.Tensor,
|
||||
]
|
||||
|
||||
|
||||
def build_paged_piecewise_plan(
|
||||
full_attn_spans: Sequence[Sequence[tuple[int, int]]],
|
||||
query_offsets: Sequence[int],
|
||||
query_lens: Sequence[int],
|
||||
seq_lens: Sequence[int],
|
||||
*,
|
||||
device: torch.device | str | None = None,
|
||||
) -> PagedPiecewisePlan:
|
||||
"""Build packed indices for corresponding piecewise segments in each row."""
|
||||
|
||||
row_count = len(full_attn_spans)
|
||||
if row_count == 0 or not (row_count == len(query_offsets) == len(query_lens) == len(seq_lens)):
|
||||
raise ValueError("Paged piecewise inputs must have one entry per row")
|
||||
|
||||
spans = tuple(tuple(tuple(span) for span in row_spans) for row_spans in full_attn_spans)
|
||||
|
||||
packed_offsets = [0]
|
||||
for row_spans, query_offset, query_len, seq_len in zip(spans, query_offsets, query_lens, seq_lens, strict=True):
|
||||
previous_end = 0
|
||||
for start, end in row_spans:
|
||||
if start < previous_end or not 0 <= start < end <= seq_len:
|
||||
raise ValueError("Paged piecewise spans must be sorted, non-overlapping, and within the sequence")
|
||||
previous_end = end
|
||||
if query_offset < 0 or query_len <= 0 or query_offset + query_len > seq_len:
|
||||
raise ValueError("Paged piecewise query range must be within the sequence")
|
||||
packed_offsets.append(packed_offsets[-1] + query_len)
|
||||
|
||||
segments_by_row = tuple(
|
||||
tuple(build_segments(row_spans, query_offset, query_len))
|
||||
for row_spans, query_offset, query_len in zip(spans, query_offsets, query_lens, strict=True)
|
||||
)
|
||||
if len({len(row_segments) for row_segments in segments_by_row}) != 1:
|
||||
raise ValueError("Paged piecewise rows must produce aligned segments")
|
||||
|
||||
packed_segments = []
|
||||
for row_segments in zip(*segments_by_row, strict=True):
|
||||
if len({segment.mode for segment in row_segments}) != 1:
|
||||
raise ValueError("Paged piecewise rows must use the same attention mode per segment")
|
||||
query_indices = []
|
||||
for row_index, (segment, query_offset) in enumerate(zip(row_segments, query_offsets, strict=True)):
|
||||
local_start = segment.q_start - query_offset
|
||||
local_end = segment.q_end - query_offset
|
||||
query_indices.extend(range(packed_offsets[row_index] + local_start, packed_offsets[row_index] + local_end))
|
||||
packed_segments.append(
|
||||
PagedPiecewiseSegment(
|
||||
row_segments=tuple(row_segments),
|
||||
query_indices=torch.tensor(query_indices, dtype=torch.long, device=device),
|
||||
)
|
||||
)
|
||||
|
||||
return PagedPiecewisePlan(spans, tuple(packed_segments), packed_offsets[-1])
|
||||
|
||||
|
||||
def run_paged_piecewise_plan(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
plan: PagedPiecewisePlan,
|
||||
segment_metadata: Sequence[object],
|
||||
segment_runner: PagedPiecewiseRunner,
|
||||
) -> torch.Tensor:
|
||||
"""Run and scatter piecewise attention over packed Q/K/V write tensors."""
|
||||
|
||||
if query.shape[0] != plan.num_query_tokens:
|
||||
raise ValueError(f"Paged piecewise plan has {plan.num_query_tokens} query tokens, got {query.shape[0]}")
|
||||
|
||||
output = None
|
||||
for segment, metadata in zip(plan.segments, segment_metadata, strict=True):
|
||||
indices = segment.query_indices
|
||||
segment_output = segment_runner(
|
||||
query.index_select(0, indices),
|
||||
key.index_select(0, indices),
|
||||
value.index_select(0, indices),
|
||||
metadata,
|
||||
)
|
||||
if output is None:
|
||||
output = segment_output.new_empty((query.shape[0], *segment_output.shape[1:]))
|
||||
output.index_copy_(0, indices, segment_output)
|
||||
|
||||
assert output is not None
|
||||
return output
|
||||
@@ -24,7 +24,11 @@ from vllm_omni.diffusion.attention.parallel.ring import RingParallelAttention
|
||||
from vllm_omni.diffusion.attention.selector import get_attn_backend_for_role
|
||||
from vllm_omni.diffusion.config import get_current_diffusion_config_or_none
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
get_forward_context,
|
||||
get_ulysses_mode,
|
||||
is_forward_context_available,
|
||||
)
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -73,6 +77,11 @@ class Attention(nn.Module):
|
||||
self.role = role
|
||||
self.role_category = role_category
|
||||
self.qkv_layout = qkv_layout
|
||||
# ``prefix`` is also the stable layer identity used by vLLM's native
|
||||
# KV-cache metadata. Keep it on the Omni layer so the active paged
|
||||
# adapter can dispatch the already-resharded Q/K/V to the matching
|
||||
# native cache tensor without replacing this Omni execution path.
|
||||
self.prefix = prefix
|
||||
if paged_kv_cache_role == "":
|
||||
raise ValueError("paged_kv_cache_role must be non-empty when provided")
|
||||
self.paged_kv_cache_role = paged_kv_cache_role
|
||||
@@ -311,19 +320,48 @@ class Attention(nn.Module):
|
||||
) -> torch.Tensor:
|
||||
# Get the appropriate parallel strategy based on SP active state
|
||||
strategy = self._get_active_parallel_strategy()
|
||||
paged_adapter = self._active_paged_kv_adapter()
|
||||
use_paged_attention = paged_adapter is not None and self.paged_kv_cache_role is not None
|
||||
if use_paged_attention and not getattr(self.attn_backend, "supports_paged_kv", False):
|
||||
raise NotImplementedError(
|
||||
f"Diffusion paged KV requires an Omni backend with paged support; "
|
||||
f"selected {self.attn_backend.get_name()}"
|
||||
)
|
||||
if use_paged_attention and strategy is not self._no_parallel_strategy:
|
||||
strategy_name = strategy.name
|
||||
if self.use_ring or strategy_name == "ring":
|
||||
raise NotImplementedError(
|
||||
"paged Scheduler KV is not supported with Ring attention; use strict Ulysses or no SP"
|
||||
)
|
||||
if strategy_name == "allgather_kv":
|
||||
raise NotImplementedError("paged Scheduler KV is not supported with AllGather-KV sequence parallelism")
|
||||
if strategy_name == "ulysses" and get_ulysses_mode(default="strict") != "strict":
|
||||
raise NotImplementedError("paged Scheduler KV currently supports only strict Ulysses")
|
||||
|
||||
# 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 = strategy.pre_attention(query, key, value, attn_metadata)
|
||||
|
||||
attn_metadata = self._with_kv_cache_dtype(attn_metadata)
|
||||
|
||||
# 2. Kernel Execution (Computation)
|
||||
if self.use_ring and strategy is not self._no_parallel_strategy:
|
||||
out = self._run_ring_attention(query, key, value, attn_metadata)
|
||||
# 2. Kernel execution stays inside the selected Omni backend. The
|
||||
# Worker adapter only prepares the native page-table context after
|
||||
# SP has produced rank-local Q/K/V tensors.
|
||||
if use_paged_attention:
|
||||
assert paged_adapter is not None
|
||||
paged_kv_context = paged_adapter.prepare_layer_context(
|
||||
self.prefix,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
omni_attn_metadata=attn_metadata,
|
||||
)
|
||||
out = self.attention.forward_paged(paged_kv_context)
|
||||
else:
|
||||
out = self._run_local_attention(query, key, value, attn_metadata)
|
||||
attn_metadata = self._with_kv_cache_dtype(attn_metadata)
|
||||
if self.use_ring and strategy is not self._no_parallel_strategy:
|
||||
out = self._run_ring_attention(query, key, value, attn_metadata)
|
||||
else:
|
||||
out = self._run_local_attention(query, key, value, attn_metadata)
|
||||
|
||||
# 3. Post-processing (Reverse Communication)
|
||||
# For Ulysses: AllToAll Output, and AllGather Joint Output
|
||||
@@ -331,6 +369,19 @@ class Attention(nn.Module):
|
||||
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _active_paged_kv_adapter():
|
||||
"""Return the opaque Worker adapter installed for this forward."""
|
||||
|
||||
if not is_forward_context_available():
|
||||
return None
|
||||
return getattr(get_forward_context(), "paged_kv_adapter", None)
|
||||
|
||||
def is_paged_kv_active(self) -> bool:
|
||||
"""Return whether this layer will use Scheduler-managed paged KV."""
|
||||
|
||||
return self.paged_kv_cache_role is not None and self._active_paged_kv_adapter() is not None
|
||||
|
||||
def _run_local_attention(self, query, key, value, attn_metadata):
|
||||
self._assert_piecewise_compatible(attn_metadata)
|
||||
|
||||
|
||||
Reference in new issue
Block a user