diff --git a/python/sglang/srt/models/kimi_k25.py b/python/sglang/srt/models/kimi_k25.py index c579c7af4153b..739adb64d639b 100644 --- a/python/sglang/srt/models/kimi_k25.py +++ b/python/sglang/srt/models/kimi_k25.py @@ -35,27 +35,47 @@ run_dp_sharded_mrope_vision_model, ) from sglang.srt.runtime_context import get_parallel, get_server_args -from sglang.srt.utils import add_prefix, is_npu +from sglang.srt.utils import add_prefix, is_cuda, is_npu logger = logging.getLogger(__name__) from sglang.srt.layers.dp_attention import is_dp_attention_enabled _is_npu = is_npu() +_is_cuda = is_cuda() + +if _is_cuda: + from sglang.jit_kernel.rope import apply_rope_inplace def apply_rope( - xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor, x_shape=None + xq: torch.Tensor, + xk: torch.Tensor, + freqs_cis: torch.Tensor | tuple[torch.Tensor, torch.Tensor], + x_shape=None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Args: (The leading dimensions of all inputs should be the same) xq: query, tensor of shape (..., num_heads, head_dim) xk: key, tensor of shape (..., num_heads, head_dim) - freqs_cis: tensor of shape (..., head_dim/2), dtype=torch.complex64. It contains the precomputed cis(freqs) for each position in the 2D grid. + freqs_cis: Either the complex frequencies used by the portable path, or + a ``(cos_sin_cache, positions)`` pair prepared for the CUDA kernel. Returns: xq_out, xk_out: tensors of shape (..., num_heads, head_dim) """ + if isinstance(freqs_cis, tuple): + cos_sin_cache, positions = freqs_cis + apply_rope_inplace( + xq, + xk, + cos_sin_cache, + positions, + is_neox=False, + rope_dim=cos_sin_cache.size(-1), + ) + return xq, xk + freqs_cis = freqs_cis.unsqueeze(-2) # ..., 1, head_dim/2 # ..., num_heads, head_dim/2 xq_ = torch.view_as_complex(xq.float().view(*xq.shape[:-1], -1, 2)) @@ -447,6 +467,7 @@ def __init__( self.rope_2d = Rope2DPosEmbRepeated( block_cfg["hidden_dim"] // block_cfg["num_heads"], 512, 512 ) + self.use_fused_rope = _is_cuda and get_server_args().rl_on_policy_target is None self.blocks = nn.ModuleList( [ MoonViTEncoderLayer( @@ -468,7 +489,21 @@ def forward( grid_thws=grid_thws, device=hidden_states.device ) - sequence_lengths = (grid_thws[:, 0] * grid_thws[:, 1] * grid_thws[:, 2]).to( + # RL target execution normalizes position embeddings to the activation + # dtype in VisionAttention, so retain the portable complex path there. + if self.use_fused_rope: + rope_freqs_cis = ( + torch.cat((rope_freqs_cis.real, rope_freqs_cis.imag), dim=-1), + torch.arange( + rope_freqs_cis.size(0), + dtype=torch.long, + device=rope_freqs_cis.device, + ), + ) + + sequence_lengths = grid_thws[:, 0] * grid_thws[:, 1] * grid_thws[:, 2] + max_seqlen = int(sequence_lengths.max().item()) + sequence_lengths = sequence_lengths.to( device=hidden_states.device, dtype=torch.int32 ) lengths = torch.cat( @@ -478,10 +513,6 @@ def forward( ) ) - # FlashAttention needs a host integer. Compute it once per MoonViT - # forward and pass it to every encoder block instead of synchronizing - # once per block inside the attention backend. - max_seqlen = int(lengths.max().item()) cu_seqlens = lengths.to(hidden_states.device).cumsum(dim=0, dtype=torch.int32) for block in self.blocks: diff --git a/test/registered/unit/layers/attention/test_vision_max_seqlen.py b/test/registered/unit/layers/attention/test_vision_max_seqlen.py index 2d83af2fa9c2c..5e71bddffc8c1 100644 --- a/test/registered/unit/layers/attention/test_vision_max_seqlen.py +++ b/test/registered/unit/layers/attention/test_vision_max_seqlen.py @@ -1,9 +1,11 @@ import sys +import pytest import torch from torch import nn from sglang.srt.layers.attention import vision +from sglang.srt.models import kimi_k25 from sglang.srt.models.kimi_k25 import MoonViT3dEncoder, MoonViTEncoderLayer from sglang.test.ci.ci_register import register_cpu_ci @@ -163,6 +165,7 @@ def forward( encoder = MoonViT3dEncoder.__new__(MoonViT3dEncoder) nn.Module.__init__(encoder) encoder.rope_2d = CapturingRope() + encoder.use_fused_rope = False encoder.blocks = nn.ModuleList([CapturingBlock()]) encoder.final_layernorm = nn.Identity() @@ -176,6 +179,110 @@ def forward( assert recorded["max_seqlen"] == 4 +def test_kimi_moonvit_computes_max_sequence_length_on_host(): + class CapturingRope: + def get_freqs_cis(self, grid_thws, device): + return torch.ones(7, 2, dtype=torch.complex64, device=device) + + encoder = MoonViT3dEncoder.__new__(MoonViT3dEncoder) + nn.Module.__init__(encoder) + encoder.rope_2d = CapturingRope() + encoder.use_fused_rope = False + encoder.blocks = nn.ModuleList() + encoder.final_layernorm = nn.Identity() + + output = encoder( + torch.ones(7, 4, device="meta"), + torch.tensor([[1, 1, 3], [1, 2, 2]], dtype=torch.int32), + ) + + assert output.device.type == "meta" + + +def test_kimi_moonvit_prepares_cuda_rope_inputs_once(monkeypatch): + recorded = {} + + class CapturingRope: + def get_freqs_cis(self, grid_thws, device): + real = torch.arange(14, dtype=torch.float32, device=device).view(7, 2) + return torch.complex(real, real + 1) + + class CapturingBlock(nn.Module): + def forward( + self, + hidden_states, + cu_seqlens, + max_seqlen, + rope_freqs_cis, + **kwargs, + ): + recorded["rope_freqs_cis"] = rope_freqs_cis + return hidden_states + + monkeypatch.setattr(kimi_k25, "_is_cuda", True) + encoder = MoonViT3dEncoder.__new__(MoonViT3dEncoder) + nn.Module.__init__(encoder) + encoder.rope_2d = CapturingRope() + encoder.use_fused_rope = True + encoder.blocks = nn.ModuleList([CapturingBlock()]) + encoder.final_layernorm = nn.Identity() + + hidden_states = torch.ones(7, 4) + encoder(hidden_states, torch.tensor([[1, 1, 7]], dtype=torch.int32)) + + cos_sin_cache, positions = recorded["rope_freqs_cis"] + assert cos_sin_cache.shape == (7, 4) + assert torch.equal(cos_sin_cache[:, :2] + 1, cos_sin_cache[:, 2:]) + assert torch.equal(positions, torch.arange(7)) + + +def test_kimi_moonvit_cuda_rope_uses_fused_inplace_kernel(monkeypatch): + recorded = {} + + def fake_apply_rope_inplace(q, k, cos_sin_cache, positions, **kwargs): + recorded.update( + cos_sin_cache=cos_sin_cache, + positions=positions, + kwargs=kwargs, + ) + q.add_(1) + k.add_(2) + + monkeypatch.setattr( + kimi_k25, "apply_rope_inplace", fake_apply_rope_inplace, raising=False + ) + q = torch.zeros(3, 2, 4) + k = torch.zeros_like(q) + cache = torch.ones(3, 4, dtype=torch.float32) + positions = torch.arange(3, dtype=torch.int64) + + q_out, k_out = kimi_k25.apply_rope(q, k, (cache, positions)) + + assert q_out is q and k_out is k + assert torch.equal(q, torch.ones_like(q)) + assert torch.equal(k, torch.full_like(k, 2)) + assert recorded["cos_sin_cache"] is cache + assert recorded["positions"] is positions + assert recorded["kwargs"] == {"is_neox": False, "rope_dim": 4} + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") +def test_kimi_moonvit_fused_rope_matches_portable_path(): + torch.manual_seed(0) + q = torch.randn(256, 4, 72, device="cuda", dtype=torch.bfloat16) + k = torch.randn_like(q) + angles = torch.randn(256, 36, device="cuda", dtype=torch.float32) + freqs_cis = torch.polar(torch.ones_like(angles), angles) + + q_ref, k_ref = kimi_k25.apply_rope(q.clone(), k.clone(), freqs_cis) + cache = torch.cat((freqs_cis.real, freqs_cis.imag), dim=-1) + positions = torch.arange(256, device="cuda", dtype=torch.long) + q_fused, k_fused = kimi_k25.apply_rope(q.clone(), k.clone(), (cache, positions)) + + torch.testing.assert_close(q_fused, q_ref, rtol=0.01, atol=0.01) + torch.testing.assert_close(k_fused, k_ref, rtol=0.01, atol=0.01) + + if __name__ == "__main__": import pytest