Merge remote-tracking branch 'upstream/main' into patches

This commit is contained in:
2026-10-05 08:52:31 +07:00
85 changed files with 3146 additions and 769 deletions
+146 -2
View File
@@ -1098,8 +1098,14 @@ def test_flashinfer_mla_dspark_dcp_supports_target_and_draft(monkeypatch):
pytest.param(False, 3, 1, 0, id="noncausal-multi-token"),
],
)
@pytest.mark.parametrize("cp_interleave_size", [1, 16, 896])
def test_tokenspeed_mla_decode_contract(
monkeypatch, causal, tokens_per_decode, dcp_world_size, dcp_rank
monkeypatch,
causal,
tokens_per_decode,
dcp_world_size,
dcp_rank,
cp_interleave_size,
):
decode_call = None
num_decodes = 2
@@ -1135,7 +1141,7 @@ def test_tokenspeed_mla_decode_contract(
impl = object.__new__(tokenspeed_mla_module.TokenspeedMLAImpl)
impl.dcp_world_size = dcp_world_size
impl.dcp_rank = dcp_rank
impl.cp_kv_cache_interleave_size = 1
impl._parallel_config = SimpleNamespace(cp_kv_cache_interleave_size=1)
impl.need_to_return_lse_for_decode = True
impl.kv_lora_rank = kv_lora_rank
impl.qk_rope_head_dim = qk_rope_head_dim
@@ -1164,6 +1170,8 @@ def test_tokenspeed_mla_decode_contract(
dtype=torch.float8_e4m3fn,
)
# NIXL may resolve the interleave size after the implementation is created.
impl._parallel_config.cp_kv_cache_interleave_size = cp_interleave_size
out, lse = impl.forward_mqa(
q,
kv_cache,
@@ -1194,6 +1202,142 @@ def test_tokenspeed_mla_decode_contract(
assert decode_call["return_lse"] is True
assert decode_call["cp_world"] == dcp_world_size
assert decode_call["cp_rank"] == dcp_rank
assert decode_call.get("cp_interleave_size", 1) == cp_interleave_size
@pytest.mark.skipif(
AttentionBackendEnum.TOKENSPEED_MLA not in BACKENDS_TO_TEST,
reason="TokenSpeed MLA requires an SM100-family GPU and tokenspeed-mla",
)
@pytest.mark.parametrize(
("cp_interleave_size", "seq_len"),
[
pytest.param(1, 5, id="token-interleave-empty-local-ranks"),
pytest.param(1, 8 + 17, id="token-interleave-full-cycle"),
pytest.param(896, 5, id="block-interleave-empty-local-ranks"),
pytest.param(896, 8 * 896 + 17, id="block-interleave-full-cycle"),
],
)
def test_tokenspeed_mla_dcp_matches_unsharded_decode(cp_interleave_size, seq_len):
from tokenspeed_mla import tokenspeed_mla_decode
from vllm.v1.attention.ops.dcp import (
_lse_weighted_combine,
mask_dcp_empty_shards_,
)
torch.manual_seed(7)
device = torch.device("cuda")
dcp_world_size = 8
kernel_block_size = 64
num_heads = 128
kv_lora_rank = 512
qk_rope_head_dim = 64
head_size = kv_lora_rank + qk_rope_head_dim
def make_paged_cache(tokens: torch.Tensor):
# Empty DCP ranks still have the null block in vLLM's physical cache.
num_pages = max(1, cdiv(tokens.shape[0], kernel_block_size))
cache = torch.zeros(
num_pages,
kernel_block_size,
head_size,
dtype=tokens.dtype,
device=device,
)
cache.view(-1, head_size)[: tokens.shape[0]].copy_(tokens)
block_table = torch.arange(
num_pages, dtype=torch.int32, device=device
).unsqueeze(0)
return cache, block_table
# Four query positions exercise the MTP/DSpark causal-mask path.
query = (torch.randn(1, 4, num_heads, head_size, device=device) * 0.1).to(
torch.float8_e4m3fn
)
global_tokens = (torch.randn(seq_len, head_size, device=device) * 0.1).to(
torch.float8_e4m3fn
)
workspace = tokenspeed_mla_module._get_workspace(device, num_heads, kv_lora_rank)
global_cache, global_block_table = make_paged_cache(global_tokens)
global_seq_len = torch.tensor([seq_len], dtype=torch.int32, device=device)
reference, _ = tokenspeed_mla_decode(
query=query,
kv_cache=global_cache,
workspace_buffer=workspace,
kv_lora_rank=kv_lora_rank,
qk_rope_head_dim=qk_rope_head_dim,
block_tables=global_block_table,
seq_lens=global_seq_len,
max_seq_len=seq_len,
softmax_scale=head_size**-0.5,
return_lse=True,
)
positions = torch.arange(seq_len, device=device)
owners = positions.div(cp_interleave_size, rounding_mode="floor").remainder(
dcp_world_size
)
max_local_seq_len = (
cdiv(seq_len, dcp_world_size * cp_interleave_size) * cp_interleave_size
)
partial_outputs = []
partial_lses = []
for dcp_rank in range(dcp_world_size):
local_tokens = global_tokens[owners == dcp_rank]
local_cache, local_block_table = make_paged_cache(local_tokens)
local_seq_len = torch.tensor(
[local_tokens.shape[0]], dtype=torch.int32, device=device
)
impl = object.__new__(tokenspeed_mla_module.TokenspeedMLAImpl)
impl.dcp_world_size = dcp_world_size
impl.dcp_rank = dcp_rank
impl._parallel_config = SimpleNamespace(
cp_kv_cache_interleave_size=cp_interleave_size
)
impl.need_to_return_lse_for_decode = True
impl.kv_lora_rank = kv_lora_rank
impl.qk_rope_head_dim = qk_rope_head_dim
impl.num_heads = num_heads
impl.scale = head_size**-0.5
impl.softmax_scale = None
impl.output_scale = None
impl._workspace_buffer = workspace
metadata = SimpleNamespace(
num_decodes=1,
num_decode_tokens=query.shape[1],
max_seq_len=max_local_seq_len,
causal=True,
decode=SimpleNamespace(
block_table=local_block_table,
seq_lens=local_seq_len,
dcp_tot_seq_lens=global_seq_len,
),
)
output, lse = impl.forward_mqa(
query.view(-1, num_heads, head_size),
local_cache,
metadata,
SimpleNamespace(_q_scale_float=1.0, _k_scale_float=1.0),
)
# Empty-shard normalization belongs to the downstream DCP combine path.
mask_dcp_empty_shards_(
lse,
local_seq_len,
torch.tensor([0, query.shape[1]], dtype=torch.int32, device=device),
)
partial_outputs.append(
output.view(query.shape[1], num_heads, kv_lora_rank).float()
)
partial_lses.append(lse.view(query.shape[1], num_heads).float())
# TokenSpeed returns base-2 LSE. Merge the per-rank partial attention states
# the same way MLADCPManager does before comparing to the unsharded result.
merged = _lse_weighted_combine(
torch.stack(partial_outputs), torch.stack(partial_lses), is_lse_base_on_e=False
).unsqueeze(0)
# FP8 attention rounds differently when KV is partitioned across DCP ranks.
torch.testing.assert_close(merged, reference.float(), atol=1e-2, rtol=1e-2)
@pytest.mark.parametrize("is_fp8_kvcache", [False, True], ids=["bf16", "fp8"])
@@ -50,6 +50,7 @@ def _create_vllm_config() -> MagicMock:
vllm_config.parallel_config = ParallelConfig()
vllm_config.speculative_config = None
vllm_config.num_speculative_tokens = 0
vllm_config.use_cumem_cudagraph_pool = False
return vllm_config
+20 -31
View File
@@ -18,6 +18,7 @@ from utils import (
import vllm.envs as envs
from vllm import LLM, SamplingParams
from vllm.inputs import TokensPrompt
@skip_unsupported
@@ -778,32 +779,16 @@ def test_decode_logprobs_match_prefill_logprobs(
print(f"[Prompt {prompt_idx}] Generated {len(token_ids)} tokens: {token_ids}")
print(f"[Prompt {prompt_idx}] Decode logprobs: {decode_logprobs.tolist()}")
# Step 2: For each token position, run prefill and compare
# Step 2: For each token position, run prefill and compare.
prompt_token_ids = list(decode_output.prompt_token_ids or [])
print(f"\n[Prompt {prompt_idx}] Verifying each token via prefill...")
for token_idx in range(len(token_ids)):
# Construct the prefix up to (but not including) this token
# Construct the prefix up to (but not including) this token using
# token ids directly.
current_token = token_ids[token_idx]
# We need to detokenize to get the text prefix
# For this, we'll use the tokenizer from the LLM
# However, the LLM API doesn't expose tokenizer easily, so we'll
# construct the prefix by decoding from the original prompt
# Get text up to this point by using the output text
# This is approximate but should work for verification
if token_idx == 0:
prefix_prompt = prompt
else:
# No per-token text, so regenerate with max_tokens = token_idx
# to get the prefix text
prefix_sp = SamplingParams(
temperature=0.0,
max_tokens=token_idx,
logprobs=1,
)
prefix_output = llm.generate([prompt], prefix_sp, use_tqdm=False)[0]
prefix_prompt = prompt + prefix_output.outputs[0].text
prefix_token_ids = prompt_token_ids + list(token_ids[:token_idx])
# Now run prefill with max_tokens=1 to get the logprob of the next token
prefill_sp = SamplingParams(
@@ -814,19 +799,23 @@ def test_decode_logprobs_match_prefill_logprobs(
print(
f" [Token {token_idx}] Running prefill for prefix "
f"(len={len(prefix_prompt)})..."
f"(num_tokens={len(prefix_token_ids)})..."
)
prefill_output = llm.generate(
[TokensPrompt(prompt_token_ids=prefix_token_ids)],
prefill_sp,
use_tqdm=False,
)[0]
prefill_logprobs, prefill_token_ids_out = _extract_step_logprobs(
prefill_output
)
prefill_output = llm.generate([prefix_prompt], prefill_sp, use_tqdm=False)[
0
]
prefill_logprobs, prefill_token_ids = _extract_step_logprobs(prefill_output)
if prefill_logprobs is None:
print(f" [Token {token_idx}] Warning: No prefill logprobs available")
continue
# The first token from prefill should match the current token
prefill_token = prefill_token_ids[0]
prefill_token = prefill_token_ids_out[0]
prefill_logprob = prefill_logprobs[0].item()
decode_logprob = decode_logprobs[token_idx].item()
@@ -851,7 +840,7 @@ def test_decode_logprobs_match_prefill_logprobs(
"decode_logprob": decode_logprob,
"prefill_logprob": prefill_logprob,
"prompt_text": prompt[:100],
"prefix_text": prefix_prompt[:100],
"prefix_token_ids": prefix_token_ids[:50],
}
)
print(f" [Token {token_idx}] ✗ TOKEN MISMATCH!")
@@ -871,7 +860,7 @@ def test_decode_logprobs_match_prefill_logprobs(
"prefill_logprob": prefill_logprob,
"diff": diff,
"prompt_text": prompt[:100],
"prefix_text": prefix_prompt[:100],
"prefix_token_ids": prefix_token_ids[:50],
"decode_all_tokens": token_ids,
"decode_all_logprobs": decode_logprobs.tolist(),
}
@@ -908,7 +897,7 @@ def test_decode_logprobs_match_prefill_logprobs(
for i, fail in enumerate(failures[:5]): # Show first 5 failures per prompt
print(f"\n [Failure {i + 1}] Token position {fail['token_idx']}:")
print(f" Reason: {fail['reason']}")
print(f" Prefix text: '{fail['prefix_text']}...'")
print(f" Prefix token ids: {fail['prefix_token_ids']}...")
print(
f" Decode: token={fail['decode_token']}, "
f"logprob={fail['decode_logprob']:.10f}"
@@ -0,0 +1,99 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Batch-invariant LoRA shrink: fixed split-K partials, fixed-order reduction."""
import pytest
import torch
from utils import skip_if_not_cuda
import vllm.lora.ops.triton_ops.lora_shrink_op as shrink_op
import vllm.lora.ops.triton_ops.utils as lora_utils
from vllm.lora.ops.triton_ops import LoRAKernelMeta, lora_shrink
from vllm.lora.ops.triton_ops.utils import _LORA_A_PTR_DICT
from vllm.utils.torch_utils import set_random_seed
DEVICE = "cuda"
@pytest.fixture(autouse=True)
def batch_invariant(monkeypatch):
monkeypatch.setattr(lora_utils, "is_batch_invariant", True)
monkeypatch.setattr(shrink_op, "is_batch_invariant", True)
lora_utils.get_lora_op_configs.cache_clear()
yield
lora_utils.get_lora_op_configs.cache_clear()
def _shrink(inputs, weights, mapping, scaling):
num_tokens = inputs.size(0)
meta = LoRAKernelMeta.make(weights[0].size(0), num_tokens, device=DEVICE)
meta.prepare_tensors(mapping)
out = torch.zeros(
(len(weights), num_tokens, weights[0].size(1)),
dtype=torch.float32,
device=DEVICE,
)
_LORA_A_PTR_DICT.clear()
args = meta.meta_args(token_nums=num_tokens, specialize_active_lora=False)
lora_shrink(inputs, weights, out, *args, scaling)
return out
@skip_if_not_cuda
@pytest.mark.parametrize(
"hidden_size,rank,nslices,dtype",
[
(2560, 8, 3, torch.bfloat16),
(9728, 16, 1, torch.float16),
(4097, 64, 1, torch.bfloat16), # K tail block
(1024, 8, 1, torch.float16), # K < 8 * BLOCK_K: some splits are empty
],
)
def test_lora_shrink_matches_reference(hidden_size, rank, nslices, dtype):
set_random_seed(0)
inputs = torch.randn((33, hidden_size), dtype=dtype, device=DEVICE)
weights = [
torch.randn((2, rank, hidden_size), dtype=dtype, device=DEVICE)
for _ in range(nslices)
]
mapping = torch.randint(-1, 2, (33,), dtype=torch.int32, device=DEVICE)
out = _shrink(inputs, weights, mapping, 0.5).double().cpu()
ids, x = mapping.cpu(), inputs.double().cpu()
ref = torch.zeros_like(out)
for s, weight in enumerate(weights):
for lora_id in (0, 1):
rows = ids == lora_id
ref[s, rows] = 0.5 * x[rows] @ weight[lora_id].double().cpu().T
torch.testing.assert_close(out, ref, rtol=5e-3, atol=5e-3)
@skip_if_not_cuda
@pytest.mark.parametrize("nslices", [1, 3])
def test_lora_shrink_invariant_across_batch_sizes(monkeypatch, nslices):
reduce_kernel, reduce_grids = shrink_op._lora_shrink_reduce_kernel, []
class RecordReduce:
def __getitem__(self, grid):
reduce_grids.append(grid)
return reduce_kernel[grid]
monkeypatch.setattr(shrink_op, "_lora_shrink_reduce_kernel", RecordReduce())
set_random_seed(0)
# K = 2560 is ten BLOCK_K=256 blocks, so all 8 splits contribute.
dtype, hidden_size = torch.bfloat16, 2560
weights = [
torch.randn((3, 16, hidden_size), dtype=dtype, device=DEVICE)
for _ in range(nslices)
]
target = torch.randn((1, hidden_size), dtype=dtype, device=DEVICE)
target_id = torch.zeros(1, dtype=torch.int32, device=DEVICE)
expected = _shrink(target, weights, target_id, 0.7)[:, 0]
for num_tokens in (31, 32, 33, 127, 128, 129):
inputs = torch.randn((num_tokens, hidden_size), dtype=dtype, device=DEVICE)
mapping = torch.randint(-1, 3, (num_tokens,), dtype=torch.int32, device=DEVICE)
pos = num_tokens // 2
inputs[pos], mapping[pos] = target[0], 0
out = _shrink(inputs, weights, mapping, 0.7)
assert torch.equal(out[:, pos], expected), num_tokens
assert len(reduce_grids) == 7
@@ -1864,6 +1864,31 @@ def test_reset_pending_lazy_stores() -> None:
assert hit_tokens == 0, "CPU cache should be empty after reset"
@pytest.mark.parametrize("num_groups", [1, 2])
@pytest.mark.parametrize("lazy", [False, True])
def test_reset_releases_pending_cpu_hits(num_groups: int, lazy: bool) -> None:
"""A lookup awaiting GPU allocation must not prevent a cache reset."""
fix = make_scheduler(num_groups=num_groups, lazy=lazy)
sched = fix.scheduler
req = make_request(num_blocks=2)
cpu_blocks = []
for group_id in range(num_groups):
cpu_blocks.extend(
_allocate_gpu_blocks(sched.cpu_block_pool, req, 2, group_id=group_id)
)
sched.cpu_block_pool.free_blocks(cpu_blocks)
assert sched.get_num_new_matched_tokens(req, 0) == (2 * BLOCK_SIZE, True)
assert all(block.ref_cnt == 1 for block in cpu_blocks)
assert not sched._reqs_to_load
assert sched.reset()
assert all(block.ref_cnt == 0 for block in cpu_blocks)
assert not sched._pending_cpu_hits
assert sched.get_num_new_matched_tokens(req, 0) == (0, False)
assert sched.reset()
# ---------------------------------------------------------------------------
# Test 14: Reset with pending loads waits for completion
# ---------------------------------------------------------------------------
+61
View File
@@ -486,6 +486,67 @@ def test_preferred_block_size_rejects_backends_with_no_common_size():
Platform._preferred_block_size_for_backends(classes, 16, None)
@pytest.mark.parametrize("cpu", [False, True])
def test_alignment_rejected_by_a_sibling_backend_raises(monkeypatch, cpu):
# Alignment that lands on a size an exact-size sibling rejects must fail
# here, not later in select_common_block_size().
backends = [_mock_backend([MultipleOf(16)]), _mock_backend([16], exact=True)]
monkeypatch.setattr(
Platform, "_find_non_ssm_backends", classmethod(lambda cls, c: backends)
)
def bump(cls, vllm_config, backend_cls):
vllm_config.cache_config.block_size = 32
monkeypatch.setattr(Platform, "_align_hybrid_block_size", classmethod(bump))
cache_config = SimpleNamespace(
block_size=16, user_specified_block_size=True, kv_cache_dtype_skip_layers=None
)
vllm_config = SimpleNamespace(
cache_config=cache_config, model_config=SimpleNamespace(is_hybrid=True)
)
from vllm.platforms.cpu import CpuPlatform # overrides the method; must check too
platform = CpuPlatform if cpu else Platform
with pytest.raises(ValueError, match="MOCK_EXACT"):
platform.update_block_size_for_backend(vllm_config)
def test_xpu_gdn_rounding_rejected_by_a_sibling_backend_raises(monkeypatch):
# XPU's GDN rounding runs after super()'s check, so it must check again.
try:
from vllm.platforms.xpu import XPUPlatform
except ImportError:
pytest.skip("vllm_xpu_kernels not importable outside an XPU stack")
backends = [_mock_backend([MultipleOf(16)]), _mock_backend([16], exact=True)]
monkeypatch.setattr(
Platform, "update_block_size_for_backend", classmethod(lambda cls, c: None)
)
monkeypatch.setattr(
Platform, "_find_non_ssm_backends", classmethod(lambda cls, c: backends)
)
gdn_layer = SimpleNamespace(
get_attn_backend=lambda: SimpleNamespace(get_name=lambda: "GDN_ATTN")
)
monkeypatch.setattr(
"vllm.config.vllm.get_layers_from_vllm_config",
lambda vllm_config, layer_type: {"gdn": gdn_layer},
)
cache_config = SimpleNamespace(
block_size=16,
mamba_cache_mode="none",
mamba_page_size_padded=None,
user_specified_block_size=True,
kv_cache_dtype_skip_layers=None,
)
vllm_config = SimpleNamespace(
cache_config=cache_config, model_config=SimpleNamespace(is_hybrid=True)
)
with pytest.raises(ValueError, match="MOCK_EXACT"):
XPUPlatform.update_block_size_for_backend(vllm_config)
def test_set_active_mm_loras_builds_tower_and_connector_mappings():
model = Mock()
model.get_mm_lora_token_counts.side_effect = (