Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 175 additions & 0 deletions tests/model_executor/test_sparse_mla_triton_warmup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import math
from types import SimpleNamespace

import pytest
import torch

from vllm.model_executor.warmup import sparse_mla_triton_warmup

# Mirrors the production runner interface: both the V1 (gpu_model_runner) and
# V2 (gpu/model_runner) runners expose ``vllm_config.parallel_config`` and
# ``dcp_rank``. The V2-only aliases ``dcp_size``/``cp_interleave`` are
# deliberately *not* provided here so that a regression to ``getattr(runner,
# "dcp_size", 1)`` silently degrades to DCP1 and fails the DCP4 assertion.
_DCP_CASES = [(1, 1, 0), (4, 64, 2)]


@pytest.mark.parametrize(
("dcp_world_size", "cp_kv_cache_interleave_size", "dcp_rank"),
_DCP_CASES,
)
def test_b12x_prefill_metadata_warmup_uses_runtime_dcp_shape(
monkeypatch,
dcp_world_size: int,
cp_kv_cache_interleave_size: int,
dcp_rank: int,
) -> None:
calls = []

class B12xBackend:
@staticmethod
def get_name() -> str:
return "B12X_MLA_SPARSE"

parallel_config = SimpleNamespace(
decode_context_parallel_size=dcp_world_size,
cp_kv_cache_interleave_size=cp_kv_cache_interleave_size,
)
runner = SimpleNamespace(
is_pooling_model=False,
device=torch.device("cpu"),
dcp_rank=dcp_rank,
vllm_config=SimpleNamespace(parallel_config=parallel_config),
attn_groups=[[SimpleNamespace(backend=B12xBackend())]],
)
worker = SimpleNamespace(
model_runner=runner,
scheduler_config=SimpleNamespace(max_num_batched_tokens=3072),
)

monkeypatch.setattr(
sparse_mla_triton_warmup,
"_warm_prefill_chunk_metadata_kernel",
lambda *args, **kwargs: calls.append((args, kwargs)),
)

sparse_mla_triton_warmup.sparse_mla_triton_warmup_if_needed(worker)

assert calls == [
(
(torch.device("cpu"),),
{
"compress_ratio": 1,
"query_len": 8,
"dcp_rank": dcp_rank,
"dcp_world_size": dcp_world_size,
"cp_kv_cache_interleave_size": cp_kv_cache_interleave_size,
},
)
]


def test_b12x_prewarm_extend_kernels_warms_ckv_plan_and_global_topk_remap(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The 96-line ``_prewarm_extend_kernels_once`` restructuring must warm both
the full-CKV local-head extend plan *and* the global top-k → gathered-CKV
remap kernel, using the runtime DCP specialization."""
import vllm.v1.attention.backends.mla.b12x_mla_sparse as b12x

# Isolate the module-level dedup set so prior tests do not short-circuit.
monkeypatch.setattr(b12x, "_EXTEND_PREWARM_DONE", set())

remap_calls: list[dict] = []
mask_calls: list = []

def fake_remap(*args, **kwargs) -> None:
remap_calls.append(kwargs)

def fake_mask(*args, **kwargs) -> None:
mask_calls.append(args)

monkeypatch.setattr(b12x, "_map_global_topk_to_gathered_ckv", fake_remap)
monkeypatch.setattr(b12x, "_mask_page_table_after_nsa_len", fake_mask)

class FakePlan:
def __init__(self, name: str) -> None:
self.name = name
self.bind_calls: list[dict] = []

def bind(self, **kwargs):
self.bind_calls.append(kwargs)
return SimpleNamespace(plan=self.name)

ckv_plan = FakePlan("ckv")
base_plan = FakePlan("base")

forward_calls: list[dict] = []

# The real method allocates tensors on ``self.device``. On a CPU-only host
# we cannot allocate on CUDA, so redirect every ``device=cuda`` allocation
# to CPU. The tensors are only ever handed to the mocked kernels/plans, so
# their backing store is irrelevant.
_real_zeros = torch.zeros
_real_empty = torch.empty
_real_full = torch.full
_real_ones = torch.ones

def _to_cpu(device):
if device is not None and str(device).startswith("cuda"):
return torch.device("cpu")
return device

def _patched(fn):
def wrapper(*args, **kwargs):
if "device" in kwargs:
kwargs["device"] = _to_cpu(kwargs["device"])
return fn(*args, **kwargs)

return wrapper

monkeypatch.setattr(torch, "zeros", _patched(_real_zeros))
monkeypatch.setattr(torch, "empty", _patched(_real_empty))
monkeypatch.setattr(torch, "full", _patched(_real_full))
monkeypatch.setattr(torch, "ones", _patched(_real_ones))

mock_self = SimpleNamespace(
device=torch.device("cuda"),
q_head_dim=576,
kv_lora_rank=512,
scale=1.0 / math.sqrt(576),
_kernel_num_heads=8,
_ckv_kernel_num_heads=8,
topk_tokens=128,
block_size=128,
need_to_return_lse_for_decode=False,
kv_cache_dtype="fp8_ds_mla",
_kv_fp8_rope=True,
_ckv_extend_plan=ckv_plan,
_extend_plan=base_plan,
dcp_world_size=4,
cp_kv_cache_interleave_size=64,
_kv_record_bytes=656,
_scratch_nbytes=1024,
_b12x_kernel_format_kwargs=lambda *a, **k: {},
_sync_warmup=lambda *a, **k: None,
_sparse_mla_extend_forward=lambda **k: forward_calls.append(k),
)

b12x.B12xMLASparseImpl._prewarm_extend_kernels_once(mock_self, 8)

# Global top-k remap prewarmed with the runtime DCP specialization.
assert len(remap_calls) == 1
assert remap_calls[0]["dcp_size"] == 4
assert remap_calls[0]["cp_kv_cache_interleave_size"] == 64
# Page-table masking ran immediately after the remap.
assert len(mask_calls) == 1
# Full-CKV local-head extend plan was warmed.
assert len(ckv_plan.bind_calls) >= 1
# Base extend plan was also warmed.
assert len(base_plan.bind_calls) >= 1
# Both plans drove at least one forward launch.
assert len(forward_calls) >= 2
49 changes: 48 additions & 1 deletion vllm/model_executor/warmup/sparse_mla_triton_warmup.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"FLASHINFER_MLA_SPARSE_SM120",
}
)
_B12X_SPARSE_MLA_BACKENDS = frozenset({"B12X_MLA_SPARSE"})
_INDEXER_PREFILL_CHUNK_METADATA_BACKENDS = frozenset({"DEEPSEEK_V32_INDEXER"})

_SPARSE_PREFILL_METADATA_NUM_PREFILLS = (1, 2, 4, 8)
Expand Down Expand Up @@ -74,6 +75,25 @@ def _hf_config_int(runner: "GPUModelRunner", name: str, default: int) -> int:
return int(getattr(hf_config, name, default) or default)


def _dcp_params(runner: "GPUModelRunner") -> tuple[int, int, int]:
"""Return ``(dcp_rank, dcp_world_size, cp_kv_cache_interleave_size)``.

Both the V1 (``gpu_model_runner``) and V2 (``gpu/model_runner``) runners
derive DCP shape from ``parallel_config``. The V2 runner also exposes
``dcp_size``/``cp_interleave`` aliases, but the V1 production runner only
defines ``dcp_world_size`` and reads the interleave from the config
directly. Reading the runner-specific aliases therefore silently fell back
to DCP1 on V1 (compiling the wrong Triton specialization); reading the
shared ``parallel_config`` source fixes that and surfaces a missing
attribute as an error instead of a silent degradation.
"""
parallel_config = runner.vllm_config.parallel_config
dcp_world_size = int(parallel_config.decode_context_parallel_size)
cp_kv_cache_interleave_size = int(parallel_config.cp_kv_cache_interleave_size)
dcp_rank = int(runner.dcp_rank)
return dcp_rank, dcp_world_size, cp_kv_cache_interleave_size


def _attention_backend_name(backend: object) -> str | None:
get_name = getattr(backend, "get_name", None)
if get_name is None:
Expand Down Expand Up @@ -140,6 +160,10 @@ def _warm_prefill_chunk_metadata_kernel(
device: torch.device,
compress_ratio: int,
query_len: int,
*,
dcp_rank: int = 0,
dcp_world_size: int = 1,
cp_kv_cache_interleave_size: int = 1,
) -> None:
from vllm.v1.attention.backends.mla.indexer import build_prefill_chunk_metadata

Expand Down Expand Up @@ -189,6 +213,9 @@ def _warm_prefill_chunk_metadata_kernel(
block_table,
compress_ratio,
query_slice=query_slice,
dcp_rank=dcp_rank,
dcp_world_size=dcp_world_size,
cp_kv_cache_interleave_size=cp_kv_cache_interleave_size,
)


Expand Down Expand Up @@ -280,10 +307,18 @@ def sparse_mla_triton_warmup(
) -> None:
device = getattr(runner, "device", torch.device("cuda"))
window_size = _hf_config_int(runner, "sliding_window", 128)
dcp_rank, dcp_world_size, cp_kv_cache_interleave_size = _dcp_params(runner)

_warm_sparse_swa_prefill_metadata_kernel(device, window_size, num_tokens)
for compress_ratio in compress_ratios:
_warm_prefill_chunk_metadata_kernel(device, compress_ratio, num_tokens)
_warm_prefill_chunk_metadata_kernel(
device,
compress_ratio,
num_tokens,
dcp_rank=dcp_rank,
dcp_world_size=dcp_world_size,
cp_kv_cache_interleave_size=cp_kv_cache_interleave_size,
)
for compress_ratio, topk, topk_width, n in combine_topk_swa_cases:
_warm_combine_topk_swa_indices_kernel(
device,
Expand Down Expand Up @@ -327,6 +362,18 @@ def sparse_mla_triton_warmup_if_needed(worker: "Worker") -> None:
num_tokens,
compress_ratios=(1,),
)
elif _has_attention_backend(runner, _B12X_SPARSE_MLA_BACKENDS):
dcp_rank, dcp_world_size, cp_kv_cache_interleave_size = _dcp_params(
runner
)
_warm_prefill_chunk_metadata_kernel(
getattr(runner, "device", torch.device("cuda")),
compress_ratio=1,
query_len=num_tokens,
dcp_rank=dcp_rank,
dcp_world_size=dcp_world_size,
cp_kv_cache_interleave_size=cp_kv_cache_interleave_size,
)
elif _has_attention_backend(runner, _INDEXER_PREFILL_CHUNK_METADATA_BACKENDS):
_warm_prefill_chunk_metadata_kernel(
getattr(runner, "device", torch.device("cuda")),
Expand Down
Loading
Loading