diff --git a/python/sglang/kernels/ops/attention/flash_attention_v4.py b/python/sglang/kernels/ops/attention/flash_attention_v4.py index 3a986fd2d4..20784c818b 100644 --- a/python/sglang/kernels/ops/attention/flash_attention_v4.py +++ b/python/sglang/kernels/ops/attention/flash_attention_v4.py @@ -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: diff --git a/python/sglang/srt/layers/attention/trtllm_mha_backend.py b/python/sglang/srt/layers/attention/trtllm_mha_backend.py index 0242936f5f..204fbb169d 100644 --- a/python/sglang/srt/layers/attention/trtllm_mha_backend.py +++ b/python/sglang/srt/layers/attention/trtllm_mha_backend.py @@ -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" diff --git a/python/sglang/srt/layers/communication/k3_sp_collective.py b/python/sglang/srt/layers/communication/k3_sp_collective.py index 6185ff7978..b46a9824ff 100644 --- a/python/sglang/srt/layers/communication/k3_sp_collective.py +++ b/python/sglang/srt/layers/communication/k3_sp_collective.py @@ -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. diff --git a/python/sglang/srt/layers/radix_attention.py b/python/sglang/srt/layers/radix_attention.py index 6840c21e2f..6dc02909ac 100644 --- a/python/sglang/srt/layers/radix_attention.py +++ b/python/sglang/srt/layers/radix_attention.py @@ -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] diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py index b4e6a15de1..3451942b4a 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py @@ -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, diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py index 8db5a0d519..a784b6de11 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py @@ -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 ) diff --git a/python/sglang/srt/models/kimi_k3.py b/python/sglang/srt/models/kimi_k3.py index 178dd80dd2..918d6369ca 100644 --- a/python/sglang/srt/models/kimi_k3.py +++ b/python/sglang/srt/models/kimi_k3.py @@ -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( diff --git a/test/registered/unit/layers/test_radix_attention.py b/test/registered/unit/layers/test_radix_attention.py index e2d7dc5a74..1fdd777967 100644 --- a/test/registered/unit/layers/test_radix_attention.py +++ b/test/registered/unit/layers/test_radix_attention.py @@ -194,6 +194,7 @@ class TestRadixAttentionGraphInterface(CustomTestCase): runner_batch = self._new_impl_context([layer], num_tokens=2).forward_batch expanded_batch = SimpleNamespace( forward_mode=ForwardMode.EXTEND, + global_num_token_non_padded_cpu=None, out_cache_loc=runner_batch.out_cache_loc, _attn_output=None, mha_return_lse=False, diff --git a/test/registered/unit/layers/test_radix_attention_padded_extend.py b/test/registered/unit/layers/test_radix_attention_padded_extend.py new file mode 100644 index 0000000000..9a62e9bb03 --- /dev/null +++ b/test/registered/unit/layers/test_radix_attention_padded_extend.py @@ -0,0 +1,250 @@ +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import torch + +from sglang.srt.layers import radix_attention +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class _RecordingBackend: + """Stand-in that checks the rows it is given against the batch's cache + locations and returns one output row per query row.""" + + def __init__(self): + self.calls = [] + + def forward(self, q, k, v, layer, forward_batch, save_kv_cache, **kwargs): + assert forward_batch.out_cache_loc.shape[0] == q.shape[0] + self.calls.append( + dict( + q=q.shape[0], + k=None if k is None else k.shape[0], + positions=forward_batch.positions.shape[0], + **{name: _rows(value) for name, value in kwargs.items()}, + ) + ) + return torch.ones(q.shape[0], 6), torch.ones(q.shape[0], 2) + + +class _OutputBackend: + """Stand-in that returns one output, written into the batch's + _attn_output when in_place is set.""" + + def __init__(self, in_place): + self.in_place = in_place + self.given = None + + def forward(self, q, k, v, layer, forward_batch, save_kv_cache, **kwargs): + self.given = forward_batch._attn_output + if self.in_place: + return self.given.fill_(3.0) + return torch.full((q.shape[0], q.shape[1]), 3.0) + + +class _IndexerBackend: + """Stand-in with a sparse indexer's contract: one index output row per + idx_q row, shaped by the query rows, as with index values enabled.""" + + def forward( + self, q, k, v, layer, forward_batch, save_kv_cache, idx_q, idx_k, idx_v + ): + assert idx_q.shape[0] == q.shape[0] + assert idx_k.shape[0] == idx_v.shape[0] == k.shape[0] + idx_out = torch.ones(idx_q.shape[0] * idx_q.shape[1] * idx_q.shape[2]) + return idx_out.reshape(q.shape[0], -1), torch.ones(q.shape[0], 2) + + +def _rows(value): + if isinstance(value, list): + return [t.shape[0] for t in value] + return value.shape[0] + + +def _batch(mode, real, rows=8): + return SimpleNamespace( + forward_mode=mode, + global_num_token_non_padded_cpu=real, + out_cache_loc=torch.arange(rows), + positions=torch.arange(rows), + mha_return_lse=False, + _attn_output=None, + ) + + +_LAYER = SimpleNamespace( + qk_head_dim=2, v_head_dim=2, tp_q_head_num=1, is_cross_attention=False +) + + +class TestPaddedExtendAttention(CustomTestCase): + """MLP sync pads an extend batch's rows to a multiple of attention TP while + its attention metadata covers only the real rows.""" + + def test_only_padded_extend_batches_are_narrowed(self): + q = torch.zeros(8, 2) + cases = [ + (ForwardMode.EXTEND, 5, 5), + (ForwardMode.EXTEND, 8, None), # nothing padded + (ForwardMode.EXTEND, 0, None), # an idle rank's batch keeps its path + (ForwardMode.TARGET_VERIFY, 5, None), + (ForwardMode.DECODE, 5, None), + ] + for mode, real, expected in cases: + with self.subTest(mode=mode, real=real): + self.assertEqual( + radix_attention.padded_extend_real_tokens(q, _batch(mode, real)), + expected, + ) + + def test_the_backend_sees_the_real_rows_and_the_tail_is_zero(self): + backend = _RecordingBackend() + batch = _batch(ForwardMode.EXTEND, 5) + out_cache_loc, positions = batch.out_cache_loc, batch.positions + with patch.object(radix_attention, "get_attn_backend", return_value=backend): + output, lse = radix_attention._attention_on_real_rows( + _LAYER, + 5, + torch.zeros(8, 2), + torch.zeros(8, 2), + torch.zeros(8, 2), + batch, + True, + q_rope=torch.zeros(8, 1), + k_rope=torch.zeros(8, 1), + ) + self.assertEqual( + backend.calls, [dict(q=5, k=5, positions=5, q_rope=5, k_rope=5)] + ) + # The batch's own tensors come back for the rest of the layer. + self.assertIs(batch.out_cache_loc, out_cache_loc) + self.assertIs(batch.positions, positions) + self.assertEqual(tuple(output.shape), (8, 6)) + torch.testing.assert_close(output[5:], torch.zeros(3, 6)) + torch.testing.assert_close(output[:5], torch.ones(5, 6)) + self.assertEqual(tuple(lse.shape), (8, 2)) + + def test_keys_with_their_own_extent_or_row_count_are_left_whole(self): + # K and V holding a cached prefix, or a cross-attention's encoder rows, + # that happen to fill the padding (8 rows) stay whole by their declared + # extent or by the layer. + cross = SimpleNamespace(**{**vars(_LAYER), "is_cross_attention": True}) + for layer, key_value_num_tokens, key_rows in ( + (_LAYER, 12, 12), + (_LAYER, None, 12), + (_LAYER, 8, 8), + (cross, None, 8), + ): + with self.subTest( + cross_attention=layer.is_cross_attention, + key_value_num_tokens=key_value_num_tokens, + ): + backend = _RecordingBackend() + with patch.object( + radix_attention, "get_attn_backend", return_value=backend + ): + radix_attention._attention_on_real_rows( + layer, + 5, + torch.zeros(8, 2), + torch.zeros(key_rows, 2), + torch.zeros(key_rows, 2), + _batch(ForwardMode.EXTEND, 5), + False, + key_value_num_tokens=key_value_num_tokens, + ) + self.assertEqual(backend.calls[0]["k"], key_rows) + + def test_per_row_inputs_follow_the_rows_they_belong_to(self): + per_row = dict( + rel_bias=torch.zeros(8, 2, 4), + aux_tensors=[torch.zeros(8, 3)], + q_descale=torch.zeros(8, 1), + mxfp8_norm_rope_positions=torch.zeros(8), + ) + for key_value_num_tokens, key_rows in ((None, 5), (12, 12)): + with self.subTest(key_value_num_tokens=key_value_num_tokens): + backend = _RecordingBackend() + with patch.object( + radix_attention, "get_attn_backend", return_value=backend + ): + radix_attention._attention_on_real_rows( + _LAYER, + 5, + torch.zeros(8, 2), + torch.zeros(8 if key_rows == 5 else key_rows, 2), + torch.zeros(8 if key_rows == 5 else key_rows, 2), + _batch(ForwardMode.EXTEND, 5), + False, + key_value_num_tokens=key_value_num_tokens, + k_descale=torch.zeros(8 if key_rows == 5 else key_rows, 1), + v_descale=torch.zeros(8 if key_rows == 5 else key_rows, 1), + **per_row, + ) + call = backend.calls[0] + self.assertEqual( + {name: call[name] for name in per_row}, + dict( + rel_bias=5, + aux_tensors=[5], + q_descale=5, + mxfp8_norm_rope_positions=5, + ), + ) + self.assertEqual( + (call["k_descale"], call["v_descale"]), (key_rows,) * 2 + ) + + def test_a_sparse_indexer_takes_the_rows_it_indexes(self): + with patch.object( + radix_attention, "get_attn_backend", return_value=_IndexerBackend() + ): + idx_out, out = radix_attention._attention_on_real_rows( + _LAYER, + 5, + torch.zeros(6, 2), + torch.zeros(6, 2), + torch.zeros(6, 2), + _batch(ForwardMode.EXTEND, 5, rows=6), + False, + idx_q=torch.zeros(6, 1, 128), + idx_k=torch.zeros(6, 128), + idx_v=torch.zeros(6, 128), + ) + self.assertEqual(idx_out.shape, (6, 128)) + self.assertEqual(out.shape, (6, 2)) + self.assertEqual(idx_out[5:].count_nonzero().item(), 0) + self.assertEqual(idx_out[:5].count_nonzero().item(), 5 * 128) + + def test_the_output_is_written_in_place_or_copied(self): + for in_place in (True, False): + with self.subTest(in_place=in_place): + backend = _OutputBackend(in_place) + batch = _batch(ForwardMode.EXTEND, 5) + with patch.object( + radix_attention, "get_attn_backend", return_value=backend + ): + output = radix_attention._attention_on_real_rows( + _LAYER, + 5, + torch.zeros(8, 2), + torch.zeros(8, 2), + torch.zeros(8, 2), + batch, + False, + ) + # The backend was handed the real rows of the returned buffer. + self.assertEqual(backend.given.data_ptr(), output.data_ptr()) + self.assertEqual(tuple(backend.given.shape), (5, 2)) + self.assertIsNone(batch._attn_output) + torch.testing.assert_close(output[:5], torch.full((5, 2), 3.0)) + torch.testing.assert_close(output[5:], torch.zeros(3, 2)) + + +if __name__ == "__main__": + unittest.main()