[Fix] Run attention on a padded extend batch's real rows (#42896)

This commit is contained in:
Cheng Wan
2026-10-09 01:26:38 -07:00
committed by GitHub
parent 7203747cc8
commit b9ae3d1a65
9 changed files with 466 additions and 120 deletions
@@ -1,5 +1,6 @@
from __future__ import annotations
import inspect
import os
from functools import lru_cache
from typing import Callable, Optional, Tuple, Union
@@ -25,6 +26,14 @@ else:
_flash_attn_import_error = None
def _takes_out(kernel) -> bool:
return kernel is not None and "out" in inspect.signature(kernel).parameters
# Released flash-attn-4 builds may lack the vendored kernel's out=.
_kernel_takes_out = _takes_out(_flash_attn_varlen_func)
def is_flash_attention_v4_available() -> bool:
return _flash_attn_varlen_func is not None
@@ -223,6 +232,7 @@ def flash_attn_varlen_func(
rel_bias: Optional[torch.Tensor] = None,
rel_bias_prep_cache: Optional[dict] = None,
return_softmax_lse: bool = False,
out: Optional[torch.Tensor] = None,
**_: object,
):
if _flash_attn_varlen_func is None: # pragma: no cover
@@ -280,6 +290,13 @@ def flash_attn_varlen_func(
rel_bias_kwargs["rel_bias"] = rel_bias
if rel_bias_prep_cache is not None:
rel_bias_kwargs["rel_bias_prep_cache"] = rel_bias_prep_cache
# The kernel writes into out, except where it pads MLA heads: its output
# then has more heads than out, and the result is a new tensor.
out_kwargs = (
{"out": out}
if out is not None and mla_head_padding is None and _kernel_takes_out
else {}
)
result = _flash_attn_varlen_func(
q=q,
k=k,
@@ -305,6 +322,7 @@ def flash_attn_varlen_func(
**sf_kwargs,
**descale_kwargs,
**rel_bias_kwargs,
**out_kwargs,
)
result = _unpad_mla_result(result, mla_head_padding)
@@ -355,6 +373,7 @@ def flash_attn_with_kvcache(
rel_bias: Optional[torch.Tensor] = None,
rel_bias_prep_cache: Optional[dict] = None,
return_softmax_lse: bool = False,
out: Optional[torch.Tensor] = None,
**_: object,
):
if k is not None or v is not None:
@@ -397,6 +416,7 @@ def flash_attn_with_kvcache(
rel_bias=rel_bias,
rel_bias_prep_cache=rel_bias_prep_cache,
return_softmax_lse=True,
out=out,
)
if return_softmax_lse:
@@ -1747,6 +1747,7 @@ class TRTLLMHAAttnBackend(FlashInferAttnBackend):
# CP must go through cp_strategy.run_attention (per-shard
# masking); the plain-causal fmha_v2 call below would be wrong.
paged_kv = torch.stack([k_cache, v_cache], dim=1)
out = forward_batch._attn_output
o = flashinfer.prefill.trtllm_fmha_v2_prefill(
(q, paged_kv),
input_layout="Q_PAGED_KV_NHD",
@@ -1760,6 +1761,7 @@ class TRTLLMHAAttnBackend(FlashInferAttnBackend):
cum_seq_lens_q=self.forward_metadata.cu_seqlens_q,
cum_seq_lens_kv=self.forward_metadata.cu_seqlens_k,
block_tables=page_table,
out=None if out is None else out.view_as(q),
out_dtype=self.q_data_type,
mask_mode=(
"padding"
@@ -9,8 +9,6 @@ the checked-in GB200/GB300 tuning envelope.
from __future__ import annotations
import logging
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Optional
import torch
@@ -47,9 +45,6 @@ class _State:
_STATE: Optional[_State] = None
_INITIALIZED = False
_O_PROJ_RESULT_BUFFERS: dict[int, torch.Tensor] = {}
_O_PROJ_OUTPUT_ROWS: ContextVar[Optional[int]] = ContextVar(
"k3_sp_o_proj_output_rows", default=None
)
def _init_state() -> Optional[_State]:
@@ -192,21 +187,6 @@ def get_o_proj_output_buffer(
return _symm_buffer(state, _O_PROJ, num_tokens, hidden_size, dtype)
@contextmanager
def o_proj_output_rows(num_rows: int):
"""Tell o_proj to target a padded full-batch symmetric output."""
token = _O_PROJ_OUTPUT_ROWS.set(num_rows)
try:
yield
finally:
_O_PROJ_OUTPUT_ROWS.reset(token)
def get_o_proj_output_rows(default: int) -> int:
num_rows = _O_PROJ_OUTPUT_ROWS.get()
return default if num_rows is None else num_rows
def register_o_proj_output(result: torch.Tensor, output: torch.Tensor) -> None:
"""Associate a model-visible o_proj result/view with its symmetric backing."""
if (
@@ -221,18 +201,6 @@ def register_o_proj_output(result: torch.Tensor, output: torch.Tensor) -> None:
_O_PROJ_RESULT_BUFFERS[result.data_ptr()] = output
def finish_padded_o_proj_output(
result: torch.Tensor, num_padded: int
) -> Optional[torch.Tensor]:
"""Zero the padding tail and return the full persistent symmetric buffer."""
output = _O_PROJ_RESULT_BUFFERS.get(result.data_ptr())
if output is None or output.shape[0] != num_padded:
return None
output[result.shape[0] :].zero_()
_O_PROJ_RESULT_BUFFERS[output.data_ptr()] = output
return output
def _resolve_symmetric_o_proj_input(tensor: torch.Tensor) -> tuple[torch.Tensor, int]:
"""Recover the persistent o_proj buffer if a model wrapper rebound its view.
+167 -23
View File
@@ -212,21 +212,7 @@ class RadixAttention(nn.Module):
idx_v=idx_v,
)
return idx_out, attn_out
# Output dtype follows v (the model dtype) when available: qk-norm
# may emit q in a different dtype without changing the dtype the
# backend writes. FP8 q/v (e.g. mxfp8 KV-cache attention) still
# produce a bf16 attention output; sizing the buffer off an fp8
# dtype would silently cast-copy the result to fp8.
out_dtype = v.dtype if v is not None else q.dtype
if out_dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
out_dtype = torch.bfloat16
if self.qk_head_dim != self.v_head_dim:
output = q.new_empty(
(q.shape[0], self.tp_q_head_num * self.v_head_dim),
dtype=out_dtype,
)
else:
output = torch.empty_like(q, dtype=out_dtype)
output = _new_attention_output(self, q, v)
if any(
key in kwargs
for key in (
@@ -291,6 +277,19 @@ class RadixAttention(nn.Module):
return output.view(-1, self.tp_q_head_num, self.v_head_dim), lse
return output
else:
real_num_tokens = padded_extend_real_tokens(q, forward_batch)
if real_num_tokens is not None:
return _attention_on_real_rows(
self,
real_num_tokens,
q,
k,
v,
forward_batch,
save_kv_cache,
key_value_num_tokens=key_value_num_tokens,
**kwargs,
)
return get_attn_backend().forward(
q,
k,
@@ -302,6 +301,158 @@ class RadixAttention(nn.Module):
)
def _new_attention_output(
layer: RadixAttention, q: torch.Tensor, v: Optional[torch.Tensor]
) -> torch.Tensor:
"""An uninitialized buffer for the layer's attention output over q's rows.
Its dtype follows v (the model dtype) when available: qk-norm may emit q in
a different dtype without changing the dtype the backend writes. FP8 q/v
(e.g. mxfp8 KV-cache attention) still produce a bf16 attention output;
sizing the buffer off an fp8 dtype would silently cast-copy the result to
fp8.
"""
out_dtype = v.dtype if v is not None else q.dtype
if out_dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
out_dtype = torch.bfloat16
if layer.qk_head_dim != layer.v_head_dim:
return q.new_empty(
(q.shape[0], layer.tp_q_head_num * layer.v_head_dim), dtype=out_dtype
)
return torch.empty_like(q, dtype=out_dtype)
# Per-row attention inputs beside Q, K and V that the tc-piecewise op schema
# cannot carry. The padded paths narrow them with the rows they belong to.
_PER_ROW_EXTRA_KWARGS = (
"rel_bias",
"q_descale",
"k_descale",
"v_descale",
"mxfp8_norm_rope_positions",
"mxfp8_norm_rope_temp_scale",
)
# The per-row inputs that follow K and V rather than the queries.
_KEY_ROW_KWARGS = frozenset({"k_rope", "k_descale", "v_descale", "idx_k", "idx_v"})
def padded_extend_real_tokens(
q: torch.Tensor, forward_batch: ForwardBatch
) -> Optional[int]:
"""The number of real rows of an extend batch that MLP sync padded to a multiple of
attention TP, whose attention metadata covers only those rows; None for a
batch without such padding. Target verify plans its padded rows itself."""
mode = forward_batch.forward_mode
if not mode.is_extend() or mode.is_target_verify():
return None
real_num_tokens = forward_batch.global_num_token_non_padded_cpu
if real_num_tokens is None or not 0 < real_num_tokens < q.shape[0]:
return None
return real_num_tokens
def _attention_on_real_rows(
layer: RadixAttention,
real_num_tokens: int,
q: torch.Tensor,
k: Optional[torch.Tensor],
v: Optional[torch.Tensor],
forward_batch: ForwardBatch,
save_kv_cache: bool,
*,
key_value_num_tokens: Optional[int] = None,
**kwargs,
):
"""Run the backend on a padded batch's real rows, with the cache locations
and positions narrowed for the call, and return its output padded back
with zero rows, as the prefill graph path does. K and V, and the per-row
inputs that follow them, are narrowed with the queries unless the caller
gives their own extent (K and V that hold a cached prefix), the layer is a
cross-attention (K and V are the encoder's), or they have a different row
count. A sparse indexer's q, k and v go with the rows they
index. A backend that writes into forward_batch._attn_output fills the
padded output's real rows in place."""
num_tokens = q.shape[0]
def queries(t):
return t[:real_num_tokens] if t is not None else None
keys_own_rows = key_value_num_tokens is not None or layer.is_cross_attention
def keys(t):
if t is None or keys_own_rows or t.shape[0] != num_tokens:
return t
return t[:real_num_tokens]
for name in (
"q_rope",
"k_rope",
"topk_indices",
"idx_q",
"idx_k",
"idx_v",
*_PER_ROW_EXTRA_KWARGS,
):
if kwargs.get(name) is not None:
narrow = keys if name in _KEY_ROW_KWARGS else queries
kwargs[name] = narrow(kwargs[name])
if kwargs.get("aux_tensors") is not None:
kwargs["aux_tensors"] = [queries(t) for t in kwargs["aux_tensors"]]
# A backend that returns more than the output (its LSE, or a sparse
# indexer's output beside it) returns a tuple, padded as it comes.
output = (
None
if kwargs.get("return_lse")
or forward_batch.mha_return_lse
or kwargs.get("idx_q") is not None
else _new_attention_output(layer, q, v)
)
out_cache_loc = forward_batch.out_cache_loc
positions = forward_batch.positions
attn_output = forward_batch._attn_output
forward_batch.out_cache_loc = out_cache_loc[:real_num_tokens]
if positions is not None:
forward_batch.positions = positions[:real_num_tokens]
if output is not None:
forward_batch._attn_output = output[:real_num_tokens]
try:
ret = get_attn_backend().forward(
queries(q),
keys(k),
keys(v),
layer,
forward_batch,
save_kv_cache,
**kwargs,
)
finally:
forward_batch.out_cache_loc = out_cache_loc
forward_batch.positions = positions
forward_batch._attn_output = attn_output
def padded(t):
if not isinstance(t, torch.Tensor) or t.shape[0] != real_num_tokens:
return t
full = t.new_empty((num_tokens, *t.shape[1:]))
full[:real_num_tokens].copy_(t)
full[real_num_tokens:].zero_()
return full
if isinstance(ret, tuple):
return tuple(padded(t) for t in ret)
if (
output is None
or not isinstance(ret, torch.Tensor)
or ret.shape[0] != real_num_tokens
or ret.numel() != output[:real_num_tokens].numel()
):
return padded(ret)
if ret.data_ptr() != output.data_ptr():
output[:real_num_tokens].view(ret.shape).copy_(ret)
output[real_num_tokens:].zero_()
return output.view(num_tokens, *ret.shape[1:])
def _unified_attention_with_output_impl(
query: torch.Tensor,
key: Optional[torch.Tensor],
@@ -630,14 +781,7 @@ def attention_with_output_extra_kwargs(
aux_tensors = kwargs.get("aux_tensors")
if aux_tensors is not None:
kwargs["aux_tensors"] = [t[:real_num_tokens] for t in aux_tensors]
for per_token_key in (
"rel_bias",
"q_descale",
"k_descale",
"v_descale",
"mxfp8_norm_rope_positions",
"mxfp8_norm_rope_temp_scale",
):
for per_token_key in _PER_ROW_EXTRA_KWARGS:
t = kwargs.get(per_token_key)
if t is not None:
kwargs[per_token_key] = t[:real_num_tokens]
@@ -299,8 +299,16 @@ class DeepseekMHAForwardMixin:
v: torch.Tensor,
forward_batch: ForwardBatch,
gate: Optional[torch.Tensor] = None,
key_value_num_tokens: Optional[int] = None,
) -> torch.Tensor:
attn_output = self.attn_mha(q, k, v, forward_batch, save_kv_cache=False)
attn_output = self.attn_mha(
q,
k,
v,
forward_batch,
save_kv_cache=False,
key_value_num_tokens=key_value_num_tokens,
)
attn_output = attn_output.reshape(-1, self.num_local_heads * self.v_head_dim)
if gate is not None:
attn_output = self._apply_gated(attn_output, gate)
@@ -422,7 +430,10 @@ class DeepseekMHAForwardMixin:
forward_batch.mha_return_lse = False
# Do mha for extended part without prefix
forward_batch.set_attn_attend_prefix_cache(False)
return self.forward_normal_core(q, k, v, forward_batch, gate)
# K and V cover every token of the sequences, the cached prefix too.
return self.forward_normal_core(
q, k, v, forward_batch, gate, key_value_num_tokens=k.shape[0]
)
def _fused_prefix_extend_attn_mha(
self: DeepseekV2AttentionMLA,
@@ -24,7 +24,10 @@ from sglang.srt.layers.dcp import (
)
from sglang.srt.layers.layer_boundary import get_attn_tp_context
from sglang.srt.layers.logits_processor import get_in_autotune_dummy_run
from sglang.srt.layers.radix_attention import unified_attention_with_output
from sglang.srt.layers.radix_attention import (
padded_extend_real_tokens,
unified_attention_with_output,
)
from sglang.srt.lora.deepseek_mla_correction import (
apply_q_correction as apply_kv_b_lora_q_correction,
)
@@ -611,7 +614,12 @@ class DeepseekMLAForwardMixin:
absorbed_bmm_concat_cast_q_fp8(
q_fp8, q_nope, self.w_kc, q_pe, self.num_local_heads
)
born_q_backend.q8kv8_stash_born_q(num_tokens, self.attn_mqa.layer_id)
# The attention call consumes the batch's real rows, a prefix of
# the rows written here.
born_q_backend.q8kv8_stash_born_q(
padded_extend_real_tokens(q_nope, forward_batch) or num_tokens,
self.attn_mqa.layer_id,
)
q_nope_out = born_q_backend.q8kv8_born_q_sentinel(
num_tokens, self.num_local_heads, self.kv_lora_rank, q_nope.device
)
+3 -61
View File
@@ -2481,9 +2481,6 @@ class KimiK3DecoderLayer(nn.Module):
self.hidden_size = config.hidden_size
self.layer_idx = layer_idx
self._dp_attention = is_dp_attention_enabled()
# mlp-sync (DP attention OR MoE a2a/EP) pads extend batches to
# attn_tp multiples; attention must then run on the real rows only.
self._trim_padded_attn = require_mlp_sync()
self._is_moe_layer = _is_moe_layer(config, layer_idx)
self._stage_boundaries = _uses_stage_boundaries(config)
# SP-MoE (EP a2a backend): o_proj defers its attention-TP reduction;
@@ -2594,7 +2591,7 @@ class KimiK3DecoderLayer(nn.Module):
_sp_inner_o_proj_forward = o_proj.forward
def _sp_o_proj_forward(x, *args, **kwargs):
output_rows = k3_sp_collective.get_o_proj_output_rows(x.shape[0])
output_rows = x.shape[0]
if k3_sp_collective.requires_symmetric_rs(
output_rows, x.device, x.element_size()
):
@@ -2718,47 +2715,8 @@ class KimiK3DecoderLayer(nn.Module):
if forward_batch.forward_mode.is_idle():
return hidden_states
# mlp-sync pads extend batches to a multiple of attn_tp_size, but the
# attention metadata covers only the real tokens: flashinfer ragged
# prefill rejects the row mismatch, and silent paths would write the
# padded rows' garbage KV through zero-padded out_cache_loc (clobbering
# pool slot 0 -> cross-request corruption). Run attention on the real
# rows and zero-pad the output back.
num_padded = hidden_states.shape[0]
num_real = num_padded
if self._trim_padded_attn and forward_batch.forward_mode.is_extend():
extend_lens = forward_batch.extend_seq_lens_cpu
if extend_lens is not None:
num_real = min(int(sum(extend_lens)), num_padded)
if num_real != num_padded:
with k3_sp_collective.o_proj_output_rows(num_padded):
attn_out = self._run_self_attn_inner(
hidden_states[:num_real],
positions[:num_real],
forward_batch,
zero_allocator,
)
padded_o_proj = k3_sp_collective.finish_padded_o_proj_output(
attn_out, num_padded
)
if padded_o_proj is not None:
return padded_o_proj
out = hidden_states.new_zeros(num_padded, attn_out.shape[-1])
out[:num_real] = attn_out
return out
return self._run_self_attn_inner(
hidden_states, positions, forward_batch, zero_allocator
)
def _run_self_attn_inner(
self,
hidden_states: torch.Tensor,
positions: torch.Tensor,
forward_batch: ForwardBatch,
zero_allocator: BumpAllocator,
) -> torch.Tensor:
# For MLA layers with q_lora_rank, set up attn_inputs before the
# forward call (normally done by the attention boundary).
# MLA layers with q_lora_rank read their latent inputs from the
# attention-TP context.
from sglang.srt.layers.layer_boundary import (
AttentionInputs,
get_attn_tp_context,
@@ -2997,7 +2955,6 @@ class KimiK3LinearModel(nn.Module):
self.pp_group = get_parallel().pp_group
self.dspark_layers_to_capture: Optional[list[int]] = None
self._dp_attention = is_dp_attention_enabled()
self._trim_padded_attn = require_mlp_sync()
self._stage_boundaries = _uses_stage_boundaries(config)
if self.pp_group.is_first_rank:
@@ -3106,21 +3063,6 @@ class KimiK3LinearModel(nn.Module):
assert isinstance(hidden_states, torch.Tensor)
assert isinstance(residual, torch.Tensor | None)
# mlp-sync (DP attention OR MoE a2a/EP) pads extend batches to a
# multiple of attn_tp_size; attention layers run on the real rows
# only (_run_self_attn trims), so the KV write locations must match
# the trimmed length. positions and hidden_states keep the padded
# length for the DP gather/scatter and the MoE.
if (
self._trim_padded_attn
and forward_batch.forward_mode.is_extend()
and forward_batch.out_cache_loc is not None
and forward_batch.extend_seq_lens_cpu is not None
):
num_real = int(sum(forward_batch.extend_seq_lens_cpu))
if forward_batch.out_cache_loc.shape[0] > num_real:
forward_batch.out_cache_loc = forward_batch.out_cache_loc[:num_real]
total_num_layers = self.end_layer - self.start_layer
device = hidden_states.device
zero_allocator = BumpAllocator(