[Model] Support Unlimited OCR (#46564)
Signed-off-by: Tianyu Guo <guoty9@mail2.sysu.edu.cn> Signed-off-by: Isotr0py <mozf@mail2.sysu.edu.cn> Co-authored-by: Isotr0py <mozf@mail2.sysu.edu.cn> Co-authored-by: Roger Wang <hey@rogerw.io>
This commit is contained in:
co-authored by
Isotr0py
Roger Wang
parent
a65f93fb2e
commit
c6741b2ad4
@@ -455,6 +455,13 @@ class CommonAttentionMetadata:
|
||||
where bidirectional attention should apply. None for text-only
|
||||
batches or non-PrefixLM models."""
|
||||
|
||||
rswa_prefix_lens: torch.Tensor | None = None
|
||||
"""(batch_size,) per-request prefix length (prompt/image token count) for
|
||||
Reference Sliding Window Attention (R-SWA). Tokens with logical index below
|
||||
this stay globally visible; later (generated) tokens additionally see a
|
||||
fixed sliding window. None disables R-SWA. The attention backend copies this
|
||||
into its own persistent buffer and reads ``rswa_window`` from model config."""
|
||||
|
||||
# WARNING: Deprecated fields. Will be removed in a future release (v0.15.0)
|
||||
_seq_lens_cpu: torch.Tensor | None = None
|
||||
_num_computed_tokens_cpu: torch.Tensor | None = None
|
||||
@@ -539,6 +546,7 @@ class CommonAttentionMetadata:
|
||||
dcp_local_seq_lens=maybe_slice_reqs(self.dcp_local_seq_lens),
|
||||
dcp_local_seq_lens_cpu=maybe_slice_reqs(self.dcp_local_seq_lens_cpu),
|
||||
is_prefilling=maybe_slice_reqs(self.is_prefilling),
|
||||
rswa_prefix_lens=maybe_slice_reqs(self.rswa_prefix_lens),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -256,6 +256,16 @@ class FlashAttentionMetadata:
|
||||
# Shape: (num_seqs, max_ranges, 2) int32, [start, end] per range.
|
||||
mm_prefix_range_tensor: torch.Tensor | None = None
|
||||
|
||||
# Reference Sliding Window Attention (R-SWA) fields.
|
||||
# rswa_prefix_lens: per-request prompt lengths [num_reqs], int32, CUDA.
|
||||
# rswa_window: sliding window size (scalar int, for logic checks).
|
||||
# rswa_window_tensor: [1] int32 CUDA tensor — pre-allocated in build() so
|
||||
# no CPU→CUDA copy is needed inside forward() during CUDA graph capture.
|
||||
# Only populated when the model uses R-SWA (Unlimited-OCR).
|
||||
rswa_prefix_lens: torch.Tensor | None = None
|
||||
rswa_window: int | None = None
|
||||
rswa_window_tensor: torch.Tensor | None = None
|
||||
|
||||
|
||||
def _get_sliding_window_configs(
|
||||
vllm_config: VllmConfig,
|
||||
@@ -386,6 +396,19 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
|
||||
# populated on first build() call.
|
||||
self.aot_sliding_window: tuple[int, int] | None = None
|
||||
|
||||
# R-SWA: persistent CUDA-graph-safe buffers owned by this builder.
|
||||
self.rswa_window: int | None = self.model_config.rswa_window
|
||||
self.persistent_rswa_prefix_lens: torch.Tensor | None = None
|
||||
self.persistent_rswa_window_tensor: torch.Tensor | None = None
|
||||
if self.rswa_window is not None:
|
||||
max_num_reqs = vllm_config.scheduler_config.max_num_seqs
|
||||
self.persistent_rswa_prefix_lens = torch.zeros(
|
||||
max_num_reqs, dtype=torch.int32, device=self.device
|
||||
)
|
||||
self.persistent_rswa_window_tensor = torch.tensor(
|
||||
[self.rswa_window], dtype=torch.int32, device=self.device
|
||||
)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
@@ -589,6 +612,22 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
|
||||
mm_ranges, num_reqs, seq_lens.device
|
||||
)
|
||||
|
||||
# R-SWA: copy prefix lengths into persistent buffers (outside the
|
||||
# compiled region) so forward() never allocates during CUDA graph
|
||||
# capture. rswa_window is a static model config scalar read here.
|
||||
if (
|
||||
self.rswa_window is not None
|
||||
and common_attn_metadata.rswa_prefix_lens is not None
|
||||
):
|
||||
assert self.persistent_rswa_prefix_lens is not None
|
||||
assert self.persistent_rswa_window_tensor is not None
|
||||
src = common_attn_metadata.rswa_prefix_lens
|
||||
rswa_prefix_lens = self.persistent_rswa_prefix_lens[:num_reqs]
|
||||
rswa_prefix_lens.copy_(src[:num_reqs], non_blocking=True)
|
||||
attn_metadata.rswa_prefix_lens = rswa_prefix_lens
|
||||
attn_metadata.rswa_window = self.rswa_window
|
||||
attn_metadata.rswa_window_tensor = self.persistent_rswa_window_tensor
|
||||
|
||||
return attn_metadata
|
||||
|
||||
def update_block_table(
|
||||
@@ -805,7 +844,7 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
)
|
||||
return output
|
||||
else:
|
||||
sliding_window_size = (
|
||||
sliding_window_size: list[int] | None = (
|
||||
list(self.sliding_window)
|
||||
if self.sliding_window is not None
|
||||
else None
|
||||
@@ -840,6 +879,25 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
mm_mask_mod = _make_mm_prefix_mask_mod(max_ranges)
|
||||
mm_aux = [mm_prefix_ranges]
|
||||
|
||||
# R-SWA: use CuTE-DSL mask_mod on FA4 for exact token-level
|
||||
# mask without block-size approximation. The mask_mod encodes
|
||||
# "causal AND (kv < prefix_len OR q - kv < rswa_window)", which
|
||||
# supersedes any FA-layer sliding_window_size parameter.
|
||||
rswa_mask_mod_fn = None
|
||||
rswa_aux = None
|
||||
if (
|
||||
attn_metadata.rswa_prefix_lens is not None
|
||||
and self.vllm_flash_attn_version == 4
|
||||
and not is_dynamic_causal
|
||||
):
|
||||
rswa_mask_mod_fn = _make_rswa_mask_mod()
|
||||
rswa_aux = [
|
||||
attn_metadata.rswa_prefix_lens.to(torch.int32),
|
||||
attn_metadata.rswa_window_tensor, # pre-allocated CUDA tensor
|
||||
]
|
||||
# mask_mod fully expresses R-SWA; disable FA's own window.
|
||||
sliding_window_size = None
|
||||
|
||||
dynamic_causal = None
|
||||
if isinstance(causal, torch.Tensor):
|
||||
if self.vllm_flash_attn_version != 4:
|
||||
@@ -873,8 +931,8 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
dynamic_causal=dynamic_causal,
|
||||
num_splits=attn_metadata.max_num_splits,
|
||||
s_aux=self.sinks,
|
||||
mask_mod=mm_mask_mod,
|
||||
aux_tensors=mm_aux,
|
||||
mask_mod=rswa_mask_mod_fn or mm_mask_mod,
|
||||
aux_tensors=rswa_aux or mm_aux,
|
||||
)
|
||||
return output
|
||||
|
||||
@@ -1152,6 +1210,59 @@ def _make_mm_prefix_mask_mod(max_ranges: int):
|
||||
return mm_prefix_mask_mod
|
||||
|
||||
|
||||
def _make_rswa_mask_mod():
|
||||
"""Build a CuTE-DSL mask_mod for Reference Sliding Window Attention (R-SWA).
|
||||
|
||||
FA4 varlen + paged-KV convention (verified from cute/mask.py apply_mask):
|
||||
q_idx = LOCAL query-token offset (0 .. seqlen_q - 1) within this sequence.
|
||||
kv_idx = LOCAL KV-token position (0 .. seqlen_k - 1) within this sequence.
|
||||
|
||||
To recover the ABSOLUTE token position (needed for causal and the sliding
|
||||
window distance), use the standard offset:
|
||||
abs_q = q_idx + (seqlen_k - seqlen_q)
|
||||
|
||||
R-SWA keep condition:
|
||||
abs_q >= kv_idx (causal: KV at or before the query)
|
||||
AND (kv_idx < prefix_len (global prefix is always visible)
|
||||
OR abs_q - kv_idx < window) (generated tokens: sliding window)
|
||||
|
||||
aux_tensors[0]: prefix_lens [num_reqs] int32 — per-request prefill length.
|
||||
aux_tensors[1]: rswa_window [1] int32 — decode sliding window size.
|
||||
|
||||
use_fast_sampling=True lets FA4 skip fully-masked KV blocks (gap blocks)
|
||||
without loading their data.
|
||||
"""
|
||||
import cutlass.cute as cute
|
||||
from cutlass import Int32 # type: ignore[attr-defined]
|
||||
|
||||
from vllm.vllm_flash_attn.cute.utils import ( # type: ignore[import-untyped]
|
||||
scalar_to_ssa,
|
||||
)
|
||||
|
||||
@cute.jit
|
||||
def rswa_mask_mod(
|
||||
batch_idx: cute.TensorSSA,
|
||||
head_idx: cute.TensorSSA,
|
||||
q_idx: cute.TensorSSA,
|
||||
kv_idx: cute.TensorSSA,
|
||||
seqlen_info,
|
||||
aux_tensors,
|
||||
):
|
||||
b = batch_idx[0]
|
||||
prefix_len = scalar_to_ssa(aux_tensors[0][b], Int32)
|
||||
window = scalar_to_ssa(aux_tensors[1][0], Int32)
|
||||
# Convert local q offset to absolute token position.
|
||||
offset = scalar_to_ssa(seqlen_info.seqlen_k - seqlen_info.seqlen_q, Int32)
|
||||
abs_q = q_idx + offset
|
||||
causal = kv_idx <= abs_q
|
||||
in_prefix = kv_idx < prefix_len
|
||||
in_window = (abs_q - kv_idx) < window
|
||||
return causal & (in_prefix | in_window)
|
||||
|
||||
rswa_mask_mod.use_fast_sampling = True
|
||||
return rswa_mask_mod
|
||||
|
||||
|
||||
def use_cascade_attention(
|
||||
common_prefix_len: int,
|
||||
query_lens: np.ndarray,
|
||||
|
||||
@@ -408,6 +408,11 @@ class FlexAttentionMetadata:
|
||||
sliding_window: int | None = None
|
||||
mm_prefix_range: dict[int, list[tuple[int, int]]] | None = None
|
||||
block_sparsity_hint: BlockSparsityHint | None = None
|
||||
# Reference Sliding Window Attention (R-SWA): per-request prefix length
|
||||
# (prompt/image tokens stay globally visible) plus a sliding window over
|
||||
# generated tokens. Both must be set to enable.
|
||||
rswa_prefix_lens: torch.Tensor | None = None
|
||||
rswa_window: int | None = None
|
||||
|
||||
@cached_property
|
||||
def logical_block_ids(self):
|
||||
@@ -571,6 +576,52 @@ class FlexAttentionMetadata:
|
||||
|
||||
return final_mask_mod
|
||||
|
||||
def get_rswa_mask_mod(self) -> _mask_mod_signature:
|
||||
"""Creates the Reference Sliding Window Attention (R-SWA) mask_mod.
|
||||
|
||||
R-SWA keeps the whole prefix (image + prompt tokens, i.e. logical index
|
||||
``< prefix_len``) globally visible while generated tokens additionally
|
||||
attend a fixed sliding window of recent tokens. This term is combined
|
||||
with the base causal mask via logical AND, so it only ever *removes*
|
||||
far-away generated tokens that fall outside the window and outside the
|
||||
prefix.
|
||||
"""
|
||||
|
||||
assert self.doc_ids is not None
|
||||
assert self.rswa_prefix_lens is not None
|
||||
assert self.rswa_window is not None
|
||||
doc_ids = self.doc_ids
|
||||
prefix_lens = self.rswa_prefix_lens
|
||||
window = self.rswa_window
|
||||
|
||||
def rswa_mask_mod(
|
||||
q_req: torch.Tensor,
|
||||
logical_q_idx: torch.Tensor,
|
||||
logical_kv_idx: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
prefix_len = prefix_lens[q_req]
|
||||
in_prefix = logical_kv_idx < prefix_len
|
||||
in_window = (logical_q_idx - logical_kv_idx) < window
|
||||
return in_prefix | in_window
|
||||
|
||||
def final_mask_mod(
|
||||
b: torch.Tensor,
|
||||
h: torch.Tensor,
|
||||
q_idx: torch.Tensor,
|
||||
physical_kv_idx: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
(is_valid, logical_q_idx, logical_kv_idx) = (
|
||||
self._convert_physical_to_logical(doc_ids, q_idx, physical_kv_idx)
|
||||
)
|
||||
q_req = doc_ids[q_idx]
|
||||
return torch.where(
|
||||
is_valid,
|
||||
rswa_mask_mod(q_req, logical_q_idx, logical_kv_idx),
|
||||
False,
|
||||
)
|
||||
|
||||
return final_mask_mod
|
||||
|
||||
def get_mask_mod(self):
|
||||
# Stage-1: initialize the base mask_mod
|
||||
# (causal mask for decoder or bidirectional mask for encoder)
|
||||
@@ -588,6 +639,10 @@ class FlexAttentionMetadata:
|
||||
# Add prefix LM mask for vision-language prefix LM attention
|
||||
prefix_lm_mask_mod = self.get_prefix_lm_mask_mod()
|
||||
mask_mod = or_masks(mask_mod, prefix_lm_mask_mod)
|
||||
if self.rswa_window is not None and self.rswa_prefix_lens is not None:
|
||||
# Reference Sliding Window Attention: AND with the base causal mask
|
||||
# (prefix stays global, generated tokens use a sliding window).
|
||||
mask_mod = and_masks(mask_mod, self.get_rswa_mask_mod())
|
||||
return mask_mod
|
||||
|
||||
def get_transformed_score_mod(self) -> _score_mod_signature | None:
|
||||
@@ -663,9 +718,21 @@ class FlexAttentionMetadata:
|
||||
self.doc_ids, : cdiv(self.max_seq_len, self.block_size)
|
||||
]
|
||||
|
||||
custom_hint = self.block_sparsity_hint is not None
|
||||
# block_table slots beyond each request's seq_len may contain garbage
|
||||
# physical page ids (see physical_to_logical_mapping). With batched
|
||||
# decode, max_seq_len is the batch max while shorter requests still
|
||||
# index all columns up to that max unless masked here.
|
||||
num_blocks = self.num_blocks_per_seq[self.doc_ids]
|
||||
past_seq = self.logical_block_ids[None, :] >= num_blocks[:, None]
|
||||
used_pages.masked_fill_(past_seq, 0)
|
||||
|
||||
if self.sliding_window or custom_hint:
|
||||
custom_hint = self.block_sparsity_hint is not None
|
||||
use_rswa = self.rswa_window is not None and self.rswa_prefix_lens is not None
|
||||
needs_per_q_pruning = (
|
||||
self.causal or self.sliding_window or custom_hint or use_rswa
|
||||
)
|
||||
|
||||
if needs_per_q_pruning:
|
||||
device = used_pages.device
|
||||
assert self.doc_ids is not None
|
||||
token_indices = torch.arange(
|
||||
@@ -676,6 +743,12 @@ class FlexAttentionMetadata:
|
||||
- self.query_start_loc[self.doc_ids]
|
||||
+ self.decode_offset[self.doc_ids]
|
||||
)
|
||||
block_starts = self.logical_block_ids * self.block_size
|
||||
block_ends = block_starts + self.block_size
|
||||
|
||||
if self.causal:
|
||||
future_blocks = block_starts[None, :] > logical_q_idx[:, None]
|
||||
used_pages.masked_fill_(future_blocks, 0)
|
||||
|
||||
if self.sliding_window:
|
||||
assert self.sliding_window is not None
|
||||
@@ -685,6 +758,23 @@ class FlexAttentionMetadata:
|
||||
min_block_idx = min_kv_idx // self.block_size
|
||||
sliding_mask = self.logical_block_ids >= min_block_idx[:, None]
|
||||
used_pages.masked_fill_(~sliding_mask, 0)
|
||||
if use_rswa:
|
||||
# R-SWA keeps prefix KV globally visible and applies a sliding
|
||||
# window over generated tokens. Prune blocks that fall entirely
|
||||
# in the "hole" between prefix_len and the current window so
|
||||
# FlexAttention does not gather invalid paged-KV slots (this
|
||||
# mirrors uniform sliding-window block pruning above).
|
||||
assert self.rswa_prefix_lens is not None
|
||||
assert self.rswa_window is not None
|
||||
prefix_len = self.rswa_prefix_lens[self.doc_ids]
|
||||
min_kv_window = torch.maximum(
|
||||
prefix_len,
|
||||
logical_q_idx - (self.rswa_window - 1),
|
||||
)
|
||||
in_gap = (block_starts[None, :] >= prefix_len[:, None]) & (
|
||||
block_ends[None, :] <= min_kv_window[:, None]
|
||||
)
|
||||
used_pages.masked_fill_(in_gap, 0)
|
||||
if custom_hint:
|
||||
assert self.block_sparsity_hint is not None
|
||||
q_block_idx = logical_q_idx // self.block_size
|
||||
@@ -798,12 +888,36 @@ class FlexAttentionMetadataBuilder(AttentionMetadataBuilder[FlexAttentionMetadat
|
||||
self.max_num_query_groups = cdiv(max_num_batched_tokens, self.q_block_size)
|
||||
max_num_pages_per_seq = cdiv(self.max_model_len, self.block_size)
|
||||
self.max_num_kv_indices = self.q_block_size * max_num_pages_per_seq
|
||||
# R-SWA uses q_block_size=1 so block lists are not merged across requests
|
||||
# in a q-group (mixed-length batches otherwise gather foreign paged-KV).
|
||||
self.max_num_rswa_query_groups = max_num_batched_tokens
|
||||
# +1 sentinel column: the flex-attention kernel's get_offset_for_next_block
|
||||
# always prefetches kv_indices[q, kv_num_blocks] (one past the last valid
|
||||
# entry) to compute the jump offset for the next loop iteration. When
|
||||
# kv_num_blocks[q] == W (every page of the sequence is live), that prefetch
|
||||
# reads column W of the persistent buffer. Without the extra column this
|
||||
# would land on stale data from a previous step (the buffer is wider than W
|
||||
# but is never fully zeroed), producing an out-of-bounds K/V pointer and a
|
||||
# CUDA illegal memory access. Allocating W_max+1 columns and initialising
|
||||
# the whole buffer to -1 ensures the sentinel slot is always safe to read.
|
||||
self.max_num_rswa_kv_indices = max_num_pages_per_seq + 1
|
||||
self.persistent_kv_num_blocks = torch.empty(
|
||||
self.max_num_query_groups, dtype=torch.int32, device=device
|
||||
)
|
||||
self.persistent_rswa_kv_num_blocks = torch.empty(
|
||||
self.max_num_rswa_query_groups, dtype=torch.int32, device=device
|
||||
)
|
||||
self.persistent_offset_tensor = torch.empty(
|
||||
max_num_seqs, dtype=torch.int32, device=device
|
||||
)
|
||||
# Persistent buffer for R-SWA per-request prefix lengths so the device
|
||||
# address stays stable across steps (required for CUDA graph replay).
|
||||
self.rswa_window: int | None = self.model_config.rswa_window
|
||||
self.persistent_rswa_prefix_lens: torch.Tensor | None = None
|
||||
if self.rswa_window is not None:
|
||||
self.persistent_rswa_prefix_lens = torch.empty(
|
||||
max_num_seqs, dtype=torch.int32, device=device
|
||||
)
|
||||
self.persistent_doc_ids = torch.empty(
|
||||
max_num_batched_tokens, dtype=torch.int32, device=device
|
||||
)
|
||||
@@ -811,6 +925,7 @@ class FlexAttentionMetadataBuilder(AttentionMetadataBuilder[FlexAttentionMetadat
|
||||
# initialize later when we can access block_table
|
||||
self.persistent_physical_to_logical = None
|
||||
self.persistent_kv_indices = None
|
||||
self.persistent_rswa_kv_indices = None
|
||||
|
||||
self.custom_logical_mask_mod: _mask_mod_signature | None = None
|
||||
if self._uses_full_cudagraphs():
|
||||
@@ -936,6 +1051,26 @@ class FlexAttentionMetadataBuilder(AttentionMetadataBuilder[FlexAttentionMetadat
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
if self.persistent_rswa_kv_indices is None:
|
||||
# Initialise to -1 so the +1 sentinel column (see max_num_rswa_kv_indices)
|
||||
# is always a safe pad value for the flex kernel's prefetch.
|
||||
self.persistent_rswa_kv_indices = torch.full(
|
||||
(self.max_num_rswa_query_groups, self.max_num_rswa_kv_indices),
|
||||
fill_value=-1,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
use_rswa = self.rswa_window is not None
|
||||
q_block_size = 1 if use_rswa else self.q_block_size
|
||||
persistent_kv_indices = (
|
||||
self.persistent_rswa_kv_indices if use_rswa else self.persistent_kv_indices
|
||||
)
|
||||
persistent_kv_num_blocks = (
|
||||
self.persistent_rswa_kv_num_blocks
|
||||
if use_rswa
|
||||
else self.persistent_kv_num_blocks
|
||||
)
|
||||
|
||||
inverse_block_table = copy_to_persistent(
|
||||
self.persistent_physical_to_logical, inverse_block_table
|
||||
@@ -944,6 +1079,13 @@ class FlexAttentionMetadataBuilder(AttentionMetadataBuilder[FlexAttentionMetadat
|
||||
offset_tensor = common_attn_metadata.compute_num_computed_tokens()
|
||||
offset_tensor = copy_to_persistent(self.persistent_offset_tensor, offset_tensor)
|
||||
|
||||
rswa_prefix_lens = common_attn_metadata.rswa_prefix_lens
|
||||
if use_rswa and rswa_prefix_lens is not None:
|
||||
assert self.persistent_rswa_prefix_lens is not None
|
||||
rswa_prefix_lens = copy_to_persistent(
|
||||
self.persistent_rswa_prefix_lens, rswa_prefix_lens
|
||||
)
|
||||
|
||||
uses_paged_kv = not isinstance(self.kv_cache_spec, EncoderOnlyAttentionSpec)
|
||||
logical_mask_mod = (
|
||||
bidirectional_mask_mod
|
||||
@@ -986,12 +1128,14 @@ class FlexAttentionMetadataBuilder(AttentionMetadataBuilder[FlexAttentionMetadat
|
||||
# attention block mask for encoder-only models, disable it temporarily.
|
||||
# see: https://github.com/vllm-project/vllm/pull/27329#issuecomment-3431484053
|
||||
direct_build=self.direct_build and uses_paged_kv,
|
||||
q_block_size=self.q_block_size,
|
||||
q_block_size=q_block_size,
|
||||
kv_block_size=self.kv_block_size,
|
||||
persistent_kv_indices=self.persistent_kv_indices,
|
||||
persistent_kv_num_blocks=self.persistent_kv_num_blocks,
|
||||
persistent_kv_indices=persistent_kv_indices,
|
||||
persistent_kv_num_blocks=persistent_kv_num_blocks,
|
||||
persistent_doc_ids=self.persistent_doc_ids,
|
||||
mm_prefix_range=common_attn_metadata.mm_req_doc_ranges,
|
||||
rswa_prefix_lens=rswa_prefix_lens,
|
||||
rswa_window=self.rswa_window,
|
||||
)
|
||||
|
||||
# Pre-build block_mask so it is ready before CUDA graph capture.
|
||||
|
||||
@@ -329,7 +329,10 @@ class KVCacheCoordinator(ABC):
|
||||
]
|
||||
|
||||
def remove_skipped_blocks(
|
||||
self, request_id: str, total_computed_tokens: int
|
||||
self,
|
||||
request_id: str,
|
||||
total_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Remove the blocks that are no longer needed from `blocks` and replace
|
||||
@@ -339,9 +342,14 @@ class KVCacheCoordinator(ABC):
|
||||
request_id: The request ID.
|
||||
total_computed_tokens: The total number of computed tokens, including
|
||||
local computed tokens and external computed tokens.
|
||||
num_prompt_tokens: Optional prompt length. R-SWA managers use this to
|
||||
free gap blocks between the prefill tail and decode window; other
|
||||
manager types ignore it.
|
||||
"""
|
||||
for manager in self.single_type_managers:
|
||||
manager.remove_skipped_blocks(request_id, total_computed_tokens)
|
||||
manager.remove_skipped_blocks(
|
||||
request_id, total_computed_tokens, num_prompt_tokens
|
||||
)
|
||||
|
||||
def get_blocks(self, request_id: str) -> tuple[list[KVCacheBlock], ...]:
|
||||
"""
|
||||
|
||||
@@ -398,7 +398,9 @@ class KVCacheManager:
|
||||
# Should call this function before allocating new blocks to reduce
|
||||
# the number of evicted blocks.
|
||||
self.coordinator.remove_skipped_blocks(
|
||||
request.request_id, total_computed_tokens
|
||||
request.request_id,
|
||||
total_computed_tokens,
|
||||
num_prompt_tokens=request.num_prompt_tokens,
|
||||
)
|
||||
|
||||
num_blocks_to_allocate = self.coordinator.get_num_blocks_to_allocate(
|
||||
@@ -468,7 +470,10 @@ class KVCacheManager:
|
||||
self.coordinator.free(request.request_id)
|
||||
|
||||
def remove_skipped_blocks(
|
||||
self, request_id: str, total_computed_tokens: int
|
||||
self,
|
||||
request_id: str,
|
||||
total_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
"""Remove the blocks that are no longer needed from `blocks` and replace
|
||||
the removed blocks with null_block.
|
||||
@@ -477,8 +482,11 @@ class KVCacheManager:
|
||||
request_id: The request ID.
|
||||
total_computed_tokens: The total number of computed tokens, including
|
||||
local computed tokens and external computed tokens.
|
||||
num_prompt_tokens: Optional prompt length for R-SWA gap eviction.
|
||||
"""
|
||||
self.coordinator.remove_skipped_blocks(request_id, total_computed_tokens)
|
||||
self.coordinator.remove_skipped_blocks(
|
||||
request_id, total_computed_tokens, num_prompt_tokens
|
||||
)
|
||||
|
||||
def pop_blocks_for_free(self, request: Request) -> list[KVCacheBlock]:
|
||||
"""Pop the request's bookkeeping and return its blocks without
|
||||
|
||||
@@ -2342,6 +2342,7 @@ class Scheduler(SchedulerInterface):
|
||||
self.kv_cache_manager.remove_skipped_blocks(
|
||||
request_id=request.request_id,
|
||||
total_computed_tokens=request.num_computed_tokens,
|
||||
num_prompt_tokens=request.num_prompt_tokens,
|
||||
)
|
||||
|
||||
block_ids = self.kv_cache_manager.get_block_ids(request.request_id)
|
||||
|
||||
@@ -20,6 +20,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
RSWASpec,
|
||||
SinkFullAttentionSpec,
|
||||
SlidingWindowMLASpec,
|
||||
SlidingWindowSpec,
|
||||
@@ -476,8 +477,38 @@ class SingleTypeKVCacheManager(ABC):
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
def _remove_blocks_in_range(
|
||||
self,
|
||||
request_id: str,
|
||||
first_block: int,
|
||||
last_block: int,
|
||||
) -> None:
|
||||
"""Free blocks in ``[first_block, last_block)`` and replace with null_block.
|
||||
|
||||
Iterates backward so newly-evictable tail blocks are reached even after
|
||||
earlier blocks in the range were nulled in a prior call.
|
||||
"""
|
||||
if request_id not in self.req_to_blocks:
|
||||
return
|
||||
if first_block >= last_block:
|
||||
return
|
||||
blocks = self.req_to_blocks[request_id]
|
||||
last_block = min(last_block, len(blocks))
|
||||
|
||||
freed: list[KVCacheBlock] = []
|
||||
for i in range(last_block - 1, first_block - 1, -1):
|
||||
if blocks[i] == self._null_block:
|
||||
break
|
||||
freed.append(blocks[i])
|
||||
blocks[i] = self._null_block
|
||||
if freed:
|
||||
self.block_pool.free_blocks(freed)
|
||||
|
||||
def remove_skipped_blocks(
|
||||
self, request_id: str, total_computed_tokens: int
|
||||
self,
|
||||
request_id: str,
|
||||
total_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Remove and free the blocks that are no longer needed for attention computation.
|
||||
@@ -490,7 +521,11 @@ class SingleTypeKVCacheManager(ABC):
|
||||
request_id: The request ID.
|
||||
total_computed_tokens: The total number of computed tokens, including
|
||||
local computed tokens and external computed tokens.
|
||||
num_prompt_tokens: Optional prompt length for attention types (e.g.
|
||||
R-SWA) that evict a middle gap rather than a head prefix. Ignored
|
||||
by the default implementation.
|
||||
"""
|
||||
del num_prompt_tokens
|
||||
# Remove the blocks that will be skipped during attention computation.
|
||||
num_skipped_tokens = self.get_num_skipped_tokens(total_computed_tokens)
|
||||
if num_skipped_tokens <= 0:
|
||||
@@ -506,18 +541,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
# range), so we must cap to the number of blocks that currently exist for
|
||||
# this request.
|
||||
num_skipped_blocks = min(num_skipped_blocks, len(blocks))
|
||||
removed_blocks: list[KVCacheBlock] = []
|
||||
# Because the block starts from index 0, the num_skipped_block-th block
|
||||
# corresponds to index num_skipped_blocks - 1.
|
||||
for i in range(num_skipped_blocks - 1, -1, -1):
|
||||
if blocks[i] == self._null_block:
|
||||
# If the block is already a null block, the blocks before it
|
||||
# should also have been set to null blocks by the previous calls
|
||||
# to this function.
|
||||
break
|
||||
removed_blocks.append(blocks[i])
|
||||
blocks[i] = self._null_block
|
||||
self.block_pool.free_blocks(removed_blocks)
|
||||
self._remove_blocks_in_range(request_id, 0, num_skipped_blocks)
|
||||
|
||||
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
|
||||
"""
|
||||
@@ -598,6 +622,50 @@ class FullAttentionManager(SingleTypeKVCacheManager):
|
||||
return num_common_blocks
|
||||
|
||||
|
||||
class RSWAManager(FullAttentionManager):
|
||||
"""KV cache manager for Reference Sliding Window Attention (R-SWA).
|
||||
|
||||
When ``num_prompt_tokens`` is supplied to ``remove_skipped_blocks``, frees
|
||||
gap blocks between the prefill tail and the current decode window. This
|
||||
bounds per-request KV memory at O(prefix_len + rswa_window) instead of
|
||||
growing linearly with decode length.
|
||||
"""
|
||||
|
||||
def __init__(self, kv_cache_spec: RSWASpec, **kwargs) -> None:
|
||||
super().__init__(kv_cache_spec, **kwargs)
|
||||
self.rswa_window: int = kv_cache_spec.rswa_window
|
||||
|
||||
def remove_skipped_blocks(
|
||||
self,
|
||||
request_id: str,
|
||||
total_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
"""Free gap blocks that are no longer needed for attention.
|
||||
|
||||
Gap = blocks entirely within
|
||||
[ceil(prefix_len / block_size) * block_size,
|
||||
max(prefix_len, total_computed_tokens - rswa_window))
|
||||
|
||||
Freed blocks are replaced with null_block in req_to_blocks so the
|
||||
block_table passed to FA4 is valid (null_block KV is all-zero;
|
||||
rswa_mask_mod marks gap positions as non-visible so FA4 skips them).
|
||||
"""
|
||||
if num_prompt_tokens is None:
|
||||
super().remove_skipped_blocks(
|
||||
request_id, total_computed_tokens, num_prompt_tokens
|
||||
)
|
||||
return
|
||||
|
||||
bs = self.block_size
|
||||
# First block fully after the prefill boundary.
|
||||
first_gap_block = cdiv(num_prompt_tokens, bs)
|
||||
# Decode window start position; blocks before this are evictable.
|
||||
window_start = max(num_prompt_tokens, total_computed_tokens - self.rswa_window)
|
||||
last_gap_block = window_start // bs # exclusive upper bound
|
||||
self._remove_blocks_in_range(request_id, first_gap_block, last_gap_block)
|
||||
|
||||
|
||||
class SlidingWindowManager(SingleTypeKVCacheManager):
|
||||
def __init__(self, kv_cache_spec: SlidingWindowSpec, **kwargs) -> None:
|
||||
super().__init__(kv_cache_spec, **kwargs)
|
||||
@@ -1072,7 +1140,12 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
|
||||
return mask
|
||||
|
||||
def remove_skipped_blocks(self, request_id: str, num_computed_tokens: int) -> None:
|
||||
def remove_skipped_blocks(
|
||||
self,
|
||||
request_id: str,
|
||||
num_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
assert isinstance(self.kv_cache_spec, MambaSpec)
|
||||
|
||||
# NOTE (tdoublep) with async scheduling, the num_computed_tokens can contain
|
||||
@@ -1082,7 +1155,9 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
# that we might actually need.
|
||||
num_computed_tokens = max(0, num_computed_tokens - self.num_speculative_blocks)
|
||||
|
||||
super().remove_skipped_blocks(request_id, num_computed_tokens)
|
||||
super().remove_skipped_blocks(
|
||||
request_id, num_computed_tokens, num_prompt_tokens
|
||||
)
|
||||
if self.mamba_cache_mode == "align":
|
||||
# `last_state_block_idx` refers to the block index allocated two steps ago.
|
||||
# The block allocated in the previous step is used to copy Mamba states
|
||||
@@ -1401,10 +1476,16 @@ def get_manager_for_kv_cache_spec(
|
||||
assert manager_class is not None, (
|
||||
f"No manager registered for KVCacheSpec {type(kv_cache_spec)}"
|
||||
)
|
||||
# SlidingWindow / ChunkedLocalAttention managers recycle blocks across
|
||||
# chunks; the runtime admission cap must match the recycling-aware bound
|
||||
# the startup pool sizer uses (single source of truth: the spec method).
|
||||
if isinstance(kv_cache_spec, (SlidingWindowSpec, ChunkedLocalAttentionSpec)):
|
||||
# SlidingWindow / ChunkedLocalAttention managers recycle blocks;
|
||||
# the runtime admission cap must match the recycling-aware bound the
|
||||
# startup pool sizer uses (single source of truth: the spec method).
|
||||
# R-SWA also recycles gap blocks but peak physical KV still fits the
|
||||
# full-attention bound (prefix + window <= max_model_len), so it inherits
|
||||
# FullAttentionSpec sizing without a separate admission cap.
|
||||
if isinstance(
|
||||
kv_cache_spec,
|
||||
(SlidingWindowSpec, ChunkedLocalAttentionSpec),
|
||||
):
|
||||
kwargs["max_admission_blocks_per_request"] = (
|
||||
kv_cache_spec.max_admission_blocks_per_request(
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
@@ -1457,6 +1538,9 @@ def register_all_kvcache_specs(vllm_config):
|
||||
KVCacheSpecRegistry.register(
|
||||
MLAAttentionSpec, FullAttentionManager, uniform_type_base_spec=FullAttentionSpec
|
||||
)
|
||||
KVCacheSpecRegistry.register(
|
||||
RSWASpec, RSWAManager, uniform_type_base_spec=FullAttentionSpec
|
||||
)
|
||||
# NOTE(Mengqing): HiddenStateCacheSpec won't take part in
|
||||
# grouping, thus the uniform_type_base_spec is just a
|
||||
# placeholder.
|
||||
|
||||
@@ -437,6 +437,46 @@ class HiddenStateCacheSpec(MLAAttentionSpec):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class RSWASpec(FullAttentionSpec):
|
||||
"""KV cache spec for Reference Sliding Window Attention (R-SWA).
|
||||
|
||||
Prefill (image + text prompt) tokens are always globally visible.
|
||||
Only the last ``rswa_window`` generated tokens are kept in the KV cache;
|
||||
gap blocks (between the prefill tail and the current decode window) are
|
||||
evicted during each decode step to bound memory at
|
||||
O(prefix_blocks + window_blocks).
|
||||
"""
|
||||
|
||||
rswa_window: int
|
||||
|
||||
@classmethod
|
||||
def merge(cls, specs: list[RSWASpec]) -> RSWASpec:
|
||||
assert all(isinstance(spec, RSWASpec) for spec in specs), (
|
||||
"All attention layers in the same KV cache group must be RSWASpec."
|
||||
)
|
||||
rswa_windows = {spec.rswa_window for spec in specs}
|
||||
assert len(rswa_windows) == 1, (
|
||||
f"All R-SWA layers must share the same rswa_window, got {rswa_windows}"
|
||||
)
|
||||
# Delegate common field merging to the parent, then reattach rswa_window.
|
||||
base = FullAttentionSpec.merge(specs) # type: ignore[arg-type]
|
||||
return cls(
|
||||
block_size=base.block_size,
|
||||
num_kv_heads=base.num_kv_heads,
|
||||
head_size=base.head_size,
|
||||
head_size_v=base.head_size_v,
|
||||
dtype=base.dtype,
|
||||
kv_quant_mode=base.kv_quant_mode,
|
||||
page_size_padded=base.page_size_padded,
|
||||
indexes_kv_by_block_stride=base.indexes_kv_by_block_stride,
|
||||
sliding_window=base.sliding_window,
|
||||
attention_chunk_size=base.attention_chunk_size,
|
||||
non_causal=base.non_causal,
|
||||
rswa_window=rswa_windows.pop(),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class ChunkedLocalAttentionSpec(AttentionSpec):
|
||||
attention_chunk_size: int
|
||||
|
||||
@@ -469,6 +469,7 @@ def build_attn_metadata(
|
||||
model_specific_attn_metadata: ModelSpecificAttnMetadata | None = None,
|
||||
for_cudagraph_capture: bool = False,
|
||||
causal: bool = True,
|
||||
rswa_prefix_lens: torch.Tensor | None = None,
|
||||
) -> dict[str, Any]:
|
||||
seq_lens = seq_lens[:num_reqs]
|
||||
if dcp_local_seq_lens is not None:
|
||||
@@ -501,6 +502,7 @@ def build_attn_metadata(
|
||||
causal=causal,
|
||||
dcp_local_seq_lens=dcp_local_seq_lens,
|
||||
positions=positions,
|
||||
rswa_prefix_lens=rswa_prefix_lens,
|
||||
**common_attn_metadata_extra_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@@ -96,6 +96,9 @@ class InputBatch:
|
||||
# Whether any requests in batch use structured output.
|
||||
has_structured_output_reqs: bool
|
||||
|
||||
# [num_reqs_after_padding] per-request prompt length for R-SWA (optional).
|
||||
rswa_prefix_lens: torch.Tensor | None = None
|
||||
|
||||
@classmethod
|
||||
def make_dummy(
|
||||
cls,
|
||||
|
||||
@@ -223,6 +223,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
max_num_tokens=self.max_num_tokens,
|
||||
device=self.device,
|
||||
)
|
||||
# R-SWA: persistent GPU buffer for per-request prefix lengths (CUDA-graph safe).
|
||||
self.rswa_prefix_lens_buffer: torch.Tensor | None = None
|
||||
if self.model_config.rswa_window is not None:
|
||||
self.rswa_prefix_lens_buffer = torch.zeros(
|
||||
self.max_num_reqs, dtype=torch.int32, device=self.device
|
||||
)
|
||||
|
||||
if self.use_pp:
|
||||
self.pp_handler = PPHandler(
|
||||
@@ -985,6 +991,16 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
if self.use_pp:
|
||||
# max_seq_len is only consumed by the PP `compute_need_sampled_mask`
|
||||
max_seq_len_np = self.req_states.max_seq_len[idx_mapping_np]
|
||||
|
||||
rswa_prefix_lens = None
|
||||
if self.rswa_prefix_lens_buffer is not None:
|
||||
rswa_prefix_lens = self.rswa_prefix_lens_buffer[:num_reqs_padded]
|
||||
rswa_prefix_lens[:num_reqs] = self.req_states.prompt_len.gpu[
|
||||
idx_mapping[:num_reqs]
|
||||
]
|
||||
if num_reqs_padded > num_reqs:
|
||||
rswa_prefix_lens[num_reqs:].zero_()
|
||||
|
||||
return InputBatch(
|
||||
req_ids=req_ids,
|
||||
num_reqs=num_reqs,
|
||||
@@ -1015,6 +1031,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
cu_num_logits=cu_num_logits,
|
||||
cu_num_logits_np=cu_num_logits_np,
|
||||
has_structured_output_reqs=scheduler_output.has_structured_output_requests,
|
||||
rswa_prefix_lens=rswa_prefix_lens,
|
||||
)
|
||||
|
||||
def prepare_attn(
|
||||
|
||||
@@ -168,5 +168,6 @@ class DefaultModelState(ModelState):
|
||||
dcp_local_seq_lens=input_batch.dcp_local_seq_lens,
|
||||
positions=input_batch.positions,
|
||||
for_cudagraph_capture=for_capture,
|
||||
rswa_prefix_lens=input_batch.rswa_prefix_lens,
|
||||
)
|
||||
return attn_metadata
|
||||
|
||||
@@ -146,6 +146,7 @@ class EncoderDecoderModelState(ModelState):
|
||||
dcp_local_seq_lens=input_batch.dcp_local_seq_lens,
|
||||
model_specific_attn_metadata=enc_dec_attn_metadata,
|
||||
for_cudagraph_capture=for_capture,
|
||||
rswa_prefix_lens=input_batch.rswa_prefix_lens,
|
||||
)
|
||||
return attn_metadata
|
||||
|
||||
|
||||
@@ -141,6 +141,7 @@ class MambaHybridModelState(DefaultModelState):
|
||||
dcp_local_seq_lens=input_batch.dcp_local_seq_lens,
|
||||
model_specific_attn_metadata=mamba_attn_metadata,
|
||||
for_cudagraph_capture=for_capture,
|
||||
rswa_prefix_lens=input_batch.rswa_prefix_lens,
|
||||
)
|
||||
|
||||
def postprocess_state(
|
||||
|
||||
@@ -2335,6 +2335,13 @@ class GPUModelRunner(
|
||||
req_idx = self.input_batch.req_id_to_index[req_id]
|
||||
req_doc_ranges[req_idx] = image_doc_ranges
|
||||
|
||||
# Reference Sliding Window Attention (R-SWA): pass per-request prompt
|
||||
# lengths so the attention backend can keep the prefix globally visible.
|
||||
# The backend owns the persistent CUDA-graph-safe GPU buffer.
|
||||
rswa_prefix_lens = None
|
||||
if self.model_config.rswa_window is not None:
|
||||
rswa_prefix_lens = num_prompt_tokens_cpu
|
||||
|
||||
cm_base = CommonAttentionMetadata(
|
||||
query_start_loc=self.query_start_loc.gpu[: num_reqs_padded + 1],
|
||||
query_start_loc_cpu=self.query_start_loc.cpu[: num_reqs_padded + 1],
|
||||
@@ -2352,6 +2359,7 @@ class GPUModelRunner(
|
||||
is_prefilling=is_prefilling,
|
||||
positions=self.positions[:num_tokens_padded],
|
||||
mm_req_doc_ranges=req_doc_ranges,
|
||||
rswa_prefix_lens=rswa_prefix_lens,
|
||||
)
|
||||
|
||||
if self.dcp_world_size > 1:
|
||||
|
||||
Reference in New Issue
Block a user