[VLM] Introduce FlashInfer CUDNN Prefill as ViT Backend (#19003)

Co-authored-by: luoyuan.luo <luoyuan.luo@antgroup.com>
This commit is contained in:
Yuan Luo
2026-02-24 19:49:22 +08:00
committed by GitHub
co-authored by luoyuan.luo
parent 1a83b2c15d
commit 31c7dc9d99
4 changed files with 678 additions and 14 deletions
@@ -34,6 +34,7 @@ _is_npu = is_npu()
_is_hip = is_hip()
if _is_cuda:
from flashinfer.prefill import cudnn_batch_prefill_with_kv_cache
from sgl_kernel.flash_attn import flash_attn_varlen_func
if _is_npu:
@@ -64,6 +65,24 @@ ROTARY_EMBED_CLASSES = {
"normal": apply_rotary_pos_emb,
}
# === Vision Encoder === #
FLASHINFER_WORKSPACE_SIZE_BYTES = 128 * 1024 * 1024
# Batch buckets for cuDNN graph caching - graphs are cached per bucket size
# This avoids creating a new graph for each unique batch size at runtime
BATCH_BUCKETS = [8, 16, 32, 64]
# Bucketized max seqlens to reduce cuDNN recompilation frequency while
# preserving a tighter upper bound than a single fixed max seqlen.
FLASHINFER_MAX_SEQLEN_BUCKETS = [
4 * 1024,
8 * 1024,
16 * 1024,
32 * 1024,
64 * 1024,
128 * 1024,
]
@dataclasses.dataclass
class SingletonCache:
@@ -452,6 +471,128 @@ class VisionFlash4Attention(nn.Module):
return output
class VisionFlashInferAttention(nn.Module):
def __init__(
self,
**kwargs,
):
if not _is_cuda:
raise Exception("VisionFlashInferAttention is only available for cuda")
super().__init__()
self.workspace_buffer = (
kwargs["workspace_buffer"] if "workspace_buffer" in kwargs else None
)
def forward(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens: torch.Tensor | SingletonCache | None,
bsz: int,
seq_len: int,
**kwargs,
) -> torch.Tensor:
r"""
Args:
cu_seqlens: [b]
Returns:
[b * s, h, head_size]
"""
if "sequence_lengths" not in kwargs:
raise RuntimeError(
"sequence_lengths should be prepared for vision flashinfer_cudnn attention backend"
)
if "max_seqlen" not in kwargs:
raise RuntimeError(
"max_seqlen should be prepared for vision flashinfer_cudnn attention backend"
)
sequence_lengths = kwargs["sequence_lengths"] # (B_padded,) or (B_padded,1,1,1)
max_seqlen = kwargs["max_seqlen"]
# max_seqlen must be python int
if isinstance(max_seqlen, torch.Tensor):
if max_seqlen.is_cuda:
max_seqlen = int(max_seqlen.detach().cpu().item())
else:
max_seqlen = int(max_seqlen.item())
else:
max_seqlen = int(max_seqlen)
# flatten if caller gives (b, s, h, d)
is_reshaped = q.dim() == 4
if is_reshaped:
reshape_batch_size = q.shape[0]
q, k, v = (rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v])
if not isinstance(cu_seqlens, torch.Tensor):
raise RuntimeError(
"flashinfer_cudnn expects packed indptrs as a torch.Tensor"
)
# sequence_lengths -> (B,)
if not isinstance(sequence_lengths, torch.Tensor):
raise RuntimeError("sequence_lengths must be a torch.Tensor")
seq_lens_1d = sequence_lengths.view(-1).to(device=q.device, dtype=torch.int32)
B = int(seq_lens_1d.numel())
# cu_seqlens contains packed *element indptrs*:
# [qk_indptr(B+1), v_indptr(B+1), o_indptr(B+1)] => total 3*(B+1)
cu_seqlens_1d = cu_seqlens.view(-1).to(device=q.device, dtype=torch.int32)
expected = 3 * (B + 1)
if int(cu_seqlens_1d.numel()) != expected:
raise RuntimeError(
f"packed indptr numel mismatch: got {cu_seqlens_1d.numel()}, expected {expected} (= 3*(B+1))"
)
split = B + 1
indptr_qk = cu_seqlens_1d[:split].view(split, 1, 1, 1)
indptr_v = cu_seqlens_1d[split : 2 * split].view(split, 1, 1, 1)
indptr_o = cu_seqlens_1d[2 * split :].view(split, 1, 1, 1)
# cuDNN style: (B,1,1,1)
seq_lens_4d = seq_lens_1d.view(B, 1, 1, 1)
# indptr are in ELEMENT offsets (not token offsets)
token_width_q = int(q.shape[1] * q.shape[2]) # heads * head_dim on this rank
total_elems_q = int(q.numel())
# check each real sequence fits
# (skip padded tail where seq_len==0)
start_elems = indptr_qk.view(-1)[:-1] # (B,)
end_elems = start_elems + seq_lens_1d * token_width_q
if (end_elems > total_elems_q).any():
raise RuntimeError("offset + len out of bounds; packed indptr is wrong")
_, _, head_size = q.shape
scale = head_size**-0.5
output, _ = cudnn_batch_prefill_with_kv_cache(
q,
k,
v,
scale,
self.workspace_buffer,
max_token_per_sequence=max_seqlen,
max_sequence_kv=max_seqlen,
actual_seq_lens_q=seq_lens_4d,
actual_seq_lens_kv=seq_lens_4d,
causal=False,
return_lse=True,
batch_offsets_q=indptr_qk,
batch_offsets_k=indptr_qk,
batch_offsets_v=indptr_v,
batch_offsets_o=indptr_o,
is_cuda_graph_compatible=True,
)
if is_reshaped:
output = rearrange(output, "(b s) h d -> b s h d", b=reshape_batch_size)
return output
class VisionAiterAttention(nn.Module):
def __init__(
self,
@@ -552,6 +693,7 @@ QKV_BACKEND_IMPL = {
"sdpa": VisionSdpaAttention,
"fa3": VisionFlash3Attention,
"fa4": VisionFlash4Attention,
"flashinfer_cudnn": VisionFlashInferAttention,
"ascend_attn": VisionAscendAttention,
"aiter_attn": VisionAiterAttention,
}
@@ -594,6 +736,7 @@ class VisionAttention(nn.Module):
use_data_parallel: bool = False,
use_dp_attention_reduce: bool = False,
aux_stream: Optional[torch.cuda.Stream] = None,
workspace_buffer: Optional[torch.Tensor] = None,
**kwargs,
):
super().__init__()
@@ -651,6 +794,7 @@ class VisionAttention(nn.Module):
flatten_batch=flatten_batch,
softmax_in_single_precision=softmax_in_single_precision,
use_data_parallel=use_data_parallel,
workspace_buffer=workspace_buffer,
)
self.use_qkv_parallel = use_qkv_parallel
@@ -686,6 +830,8 @@ class VisionAttention(nn.Module):
prefix=add_prefix("proj", prefix),
use_dp_attention_reduce=use_dp_attention_reduce,
)
self.workspace_buffer = workspace_buffer
self.aux_stream = aux_stream
self.ln_events = [torch.cuda.Event(), torch.cuda.Event()] if aux_stream else []
@@ -829,6 +975,10 @@ class VisionAttention(nn.Module):
kv_head = self.num_attention_kv_heads_per_partition
attn_output_ws = kwargs["output_ws"] if "output_ws" in kwargs else None
max_seqlen = kwargs["max_seqlen"] if "max_seqlen" in kwargs else None
sequence_lengths = (
kwargs["sequence_lengths"] if "sequence_lengths" in kwargs else None
)
if self.use_qkv_parallel:
# [b, s, embed_dim] --> [b, s, embed_dim]
qkv, _ = self.qkv_proj(x)
@@ -935,6 +1085,8 @@ class VisionAttention(nn.Module):
seq_len=s,
cu_seqlens=cu_seqlens,
attention_mask=attention_mask,
sequence_lengths=sequence_lengths,
max_seqlen=max_seqlen,
output_ws=attn_output_ws,
)