diff --git a/csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu b/csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu index d8460f032eb2..05987fe70d48 100644 --- a/csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu +++ b/csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu @@ -281,7 +281,7 @@ __device__ __forceinline__ void storeElemsFp8( // Slots per token: // Q : nq (always — norm+RoPE) // K : nkv (always — norm+RoPE; +K-cache insert) -// V : nkv only if kInsertKV (V-cache insert; no warps in dense) +// V : nkv only if kInsertKV (V-cache insert) // IQ: niq only if kProcessIndex (norm+RoPE) // IK: 1 only if kProcessIndex (norm+RoPE; +index-cache insert) // cache_t/kv_dt: main attention KV-cache dtype (auto/fp8). out_idx_t/kFp8Idx: @@ -583,9 +583,12 @@ void launchFusedMiniMaxM3( LAUNCH(true, false, true, false, scalar_t); // sparse profiling, bf16 } } + } else if (insert_kv) { + // Dense layer with the KV insert fused in (the generic Attention layer + // skips its own cache update). + LAUNCH(false, true, false, false, scalar_t); } else { - // Dense layer: never has an index branch and never inserts here (the - // generic Attention layer owns the KV insert). + // Dense layer, norm+RoPE only (profiling run or non-fusable backend). LAUNCH(false, false, false, false, scalar_t); } #undef LAUNCH @@ -699,11 +702,6 @@ void fused_minimax_m3_qknorm_rope_kv_insert( " + num_index_heads + 1) * 128 for sparse, " "(num_heads + 2*num_kv_heads) * 128 for dense"); - // Only the sparse layer inserts here (dense lets the generic Attention layer - // own the KV write); there is no dense+insert kernel instantiation. - STD_TORCH_CHECK( - !insert_kv || has_index, - "insert mode (kv_cache) requires the index branch (sparse layer)"); STD_TORCH_CHECK(has_index || !skip_index_branch, "skip_index_branch requires sparse qkv rows"); if (process_index) { diff --git a/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py b/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py index 5c762b63df43..afbe9f0389e7 100644 --- a/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py +++ b/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py @@ -137,7 +137,116 @@ def test_dense_norm_rope(num_tokens, num_heads, num_kv_heads): torch.testing.assert_close(v_out, v_in, rtol=0, atol=0) -# ── Test 2: sparse mode (full: index branch + cache inserts) ───────────────── +# ── Test 2: dense mode with fused KV insert (no index branch) ──────────────── + + +@pytest.mark.parametrize("num_tokens", [1, 7, 64, 513]) +@pytest.mark.parametrize("block_size", [16, 64]) +@pytest.mark.parametrize("cache_layout", ["HND", "NHD"]) +def test_dense_kv_insert(num_tokens, block_size, cache_layout): + """Dense rows ([q|k|v], no index tail) with kv_cache: k/v must land in the + paged cache like the generic Attention's separate reshape_and_cache would + write them, honoring both NHD and HND physical layouts via strides, and + padded tokens (slot -1) must be skipped.""" + torch.manual_seed(2) + device, dtype, eps = "cuda", torch.bfloat16, 1e-6 + base, max_pos = 5_000_000.0, 4096 + num_heads, num_kv_heads = 16, 4 + + q_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + k_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + cos_sin = make_cos_sin_cache(max_pos, ROTARY_DIM, base, dtype, device) + positions = torch.randint( + 0, max_pos, (num_tokens,), dtype=torch.int64, device=device + ) + + qsz, kvsz = num_heads * HEAD_DIM, num_kv_heads * HEAD_DIM + qkv = torch.randn(num_tokens, qsz + 2 * kvsz, dtype=dtype, device=device) + qkv_orig = qkv.clone() + + num_blocks = (num_tokens + block_size - 1) // block_size + 1 + if cache_layout == "HND": + kv_cache = torch.zeros( + num_blocks, + num_kv_heads, + block_size, + 2 * HEAD_DIM, + dtype=dtype, + device=device, + ) + else: + # Logical [nb, nkv, bs, 2*hd] view over NHD physical storage. + kv_cache = torch.zeros( + num_blocks, + block_size, + num_kv_heads, + 2 * HEAD_DIM, + dtype=dtype, + device=device, + ).permute(0, 2, 1, 3) + slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + if num_tokens > 1: + slot_mapping[-1] = -1 # cudagraph-padded / unscheduled token + + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + q_w, + k_w, + cos_sin, + positions, + num_heads, + num_kv_heads, + ROTARY_DIM, + eps, + slot_mapping=slot_mapping, + kv_cache=kv_cache, + block_size=block_size, + kv_cache_dtype="auto", + ) + + q_out, k_out, v_out = qkv.split([qsz, kvsz, kvsz], dim=-1) + q_in, k_in, v_in = qkv_orig.split([qsz, kvsz, kvsz], dim=-1) + q_ref = norm_rope_ref( + q_in.view(num_tokens, num_heads, HEAD_DIM), q_w, positions, cos_sin, eps + ).view(num_tokens, qsz) + k_ref = norm_rope_ref( + k_in.view(num_tokens, num_kv_heads, HEAD_DIM), + k_w, + positions, + cos_sin, + eps, + ).view(num_tokens, kvsz) + torch.testing.assert_close(q_out, q_ref, rtol=1e-2, atol=1e-2) + torch.testing.assert_close(k_out, k_ref, rtol=1e-2, atol=1e-2) + torch.testing.assert_close(v_out, v_in, rtol=0, atol=0) + + # Cache K is the same fp32->bf16 store as the in-place k_out (bit-exact); + # V is copied raw. + k_out_h = k_out.view(num_tokens, num_kv_heads, HEAD_DIM) + v_ref_h = v_in.view(num_tokens, num_kv_heads, HEAD_DIM) + written = torch.zeros(num_blocks * block_size, dtype=torch.bool) + for t in range(num_tokens): + s = slot_mapping[t].item() + if s < 0: + continue + written[s] = True + b, pos = s // block_size, s % block_size + torch.testing.assert_close( + kv_cache[b, :, pos, :HEAD_DIM], k_out_h[t], rtol=0, atol=0 + ) + torch.testing.assert_close( + kv_cache[b, :, pos, HEAD_DIM:], v_ref_h[t], rtol=0, atol=0 + ) + # Slots not in the mapping (including the padded token's) stay zero. + untouched = kv_cache.transpose(1, 2).reshape(num_blocks * block_size, -1)[ + ~written.to(device) + ] + assert (untouched == 0).all() + + +# ── Test 3: sparse mode (full: index branch + cache inserts) ───────────────── @pytest.mark.parametrize("num_tokens", [1, 7, 64, 513]) diff --git a/vllm/_custom_ops.py b/vllm/_custom_ops.py index 9fcc4ae87e8e..963cac0f96cf 100644 --- a/vllm/_custom_ops.py +++ b/vllm/_custom_ops.py @@ -2572,11 +2572,13 @@ def fused_minimax_m3_qknorm_rope_kv_insert( - sparse layer (``num_index_heads > 0``): ``[q | k | v | index_q | index_k]`` — the index branch is read straight out of ``qkv``. - When ``kv_cache`` is given (sparse serving), also scatter-inserts the - normed/roped k & v into the paged KV cache by ``slot_mapping`` and the - index key into ``index_cache`` by ``index_slot_mapping``. ``kv_cache_dtype`` - selects the cache storage/conversion path. If - ``index_slot_mapping`` is omitted, ``slot_mapping`` is used for both caches. + When ``kv_cache`` is given (dense or sparse serving), also scatter-inserts + the normed/roped k & v into the paged KV cache (logical layout + ``[nb, nkv, bs, 2*head_dim]``) by ``slot_mapping``; on sparse layers the + index key is likewise inserted into ``index_cache`` by + ``index_slot_mapping``. ``kv_cache_dtype`` selects the cache + storage/conversion path. If ``index_slot_mapping`` is omitted, + ``slot_mapping`` is used for both caches. If ``q_out`` / ``index_q_out`` (contiguous ``[N, nq*128]`` / ``[N, niq*128]``) are given, the normed/roped q / index_q are written there diff --git a/vllm/model_executor/layers/attention/attention.py b/vllm/model_executor/layers/attention/attention.py index d8c4cf80ba96..3b56c7ce0500 100644 --- a/vllm/model_executor/layers/attention/attention.py +++ b/vllm/model_executor/layers/attention/attention.py @@ -451,6 +451,12 @@ def __init__( compilation_config.static_forward_context, ) self.kv_sharing_target_layer_name = kv_sharing_target_layer_name + # When True, the owning model layer inserts this step's k/v into the + # paged cache itself (fused into a preceding kernel), so forward() + # skips the separate unified_kv_cache_update. Set post-init by the + # owning layer; only valid when the backend performs the KV update as + # a separate step (forward_includes_kv_cache_update == False). + self.skip_kv_cache_update_by_layer = False # Gemma4: clamp mm_prefix bidirectional ranges by the sliding window # (read by the Triton backend impl). Default False for all other models. self.mm_prefix_clamp_sliding_window = mm_prefix_clamp_sliding_window @@ -539,10 +545,12 @@ def forward( value = value.view(-1, self.num_kv_heads, self.head_size_v) kv_cache_dummy_dep = None if self.use_direct_call: - # Skip this if sharing KV cache with an earlier attention layer. + # Skip this if sharing KV cache with an earlier attention layer + # or if the model layer already inserted k/v itself. if ( not self.attn_backend.forward_includes_kv_cache_update and self.kv_sharing_target_layer_name is None + and not self.skip_kv_cache_update_by_layer and key is not None and value is not None ): @@ -558,11 +566,13 @@ def forward( kv_cache_dummy_dep=kv_cache_dummy_dep, ) else: - # Skip this if sharing KV cache with an earlier attention layer. + # Skip this if sharing KV cache with an earlier attention layer + # or if the model layer already inserted k/v itself. encoded = _encode_layer_name(self.layer_name) if ( not self.attn_backend.forward_includes_kv_cache_update and self.kv_sharing_target_layer_name is None + and not self.skip_kv_cache_update_by_layer and key is not None and value is not None ): diff --git a/vllm/models/minimax_m3/nvidia/model.py b/vllm/models/minimax_m3/nvidia/model.py index e29514ab9a32..c8762328dba4 100644 --- a/vllm/models/minimax_m3/nvidia/model.py +++ b/vllm/models/minimax_m3/nvidia/model.py @@ -358,6 +358,14 @@ def __init__( quant_config=quant_config, prefix=f"{prefix}.attn", ) + # Fuse the KV insert into the qknorm+rope kernel when the backend runs + # the KV update as a separate step this layer can take over. All such + # backends keep the paged cache in the [nb, nkv, bs, 2*hd] layout the + # kernel writes; its host checks fail loudly otherwise. + self.fuse_kv_insert = ( + not self.attn.attn_backend.forward_includes_kv_cache_update + ) + self.attn.skip_kv_cache_update_by_layer = self.fuse_kv_insert def forward( self, @@ -366,19 +374,41 @@ def forward( ) -> torch.Tensor: qkv, _ = self.qkv_proj(hidden_states) # Fused per-head Gemma QK-norm + partial NeoX RoPE on q/k, in place. - - ops.fused_minimax_m3_qknorm_rope_kv_insert( - qkv, - self.q_norm.weight, - self.k_norm.weight, - self.rotary_emb.cos_sin_cache, - positions, - self.num_heads, - self.num_kv_heads, - self.rotary_emb.rotary_dim, - self.q_norm.variance_epsilon, - kv_cache_dtype="auto", - ) + slot_mapping = None + if self.fuse_kv_insert: + fwd_slot_mapping = get_forward_context().slot_mapping + if isinstance(fwd_slot_mapping, dict): + slot_mapping = fwd_slot_mapping.get(self.attn.layer_name) + if slot_mapping is not None: + kv_cache = self.attn.kv_cache + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + self.q_norm.weight, + self.k_norm.weight, + self.rotary_emb.cos_sin_cache, + positions, + self.num_heads, + self.num_kv_heads, + self.rotary_emb.rotary_dim, + self.q_norm.variance_epsilon, + slot_mapping=slot_mapping, + kv_cache=kv_cache, + block_size=kv_cache.size(2), + kv_cache_dtype="auto", + ) + else: + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + self.q_norm.weight, + self.k_norm.weight, + self.rotary_emb.cos_sin_cache, + positions, + self.num_heads, + self.num_kv_heads, + self.rotary_emb.rotary_dim, + self.q_norm.variance_epsilon, + kv_cache_dtype="auto", + ) q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) attn_output = self.attn(q, k, v) output, _ = self.o_proj(attn_output)