[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
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user