Merge branch 'main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -191,3 +191,106 @@ def test_amd_attn_res_fused_contract(
|
||||
original_blocks[:, block_write_idx].copy_(expected_prefix)
|
||||
torch.testing.assert_close(blocks, original_blocks, atol=0, rtol=0)
|
||||
assert actual.is_contiguous()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"num_tokens,num_blocks,has_delta,write_block",
|
||||
[
|
||||
(0, 0, False, False),
|
||||
(1, 0, True, True),
|
||||
(17, 4, True, True),
|
||||
(320, 8, False, False),
|
||||
],
|
||||
)
|
||||
def test_amd_attn_res_fp8_preserves_prefix_and_quantized_output(
|
||||
num_tokens,
|
||||
num_blocks,
|
||||
has_delta,
|
||||
write_block,
|
||||
default_vllm_config,
|
||||
):
|
||||
from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
|
||||
|
||||
torch.manual_seed(41)
|
||||
hidden_size = 7168
|
||||
prefix = _randn_with_row_padding(num_tokens, hidden_size, padding=7)
|
||||
delta = _randn_with_row_padding(num_tokens, hidden_size) if has_delta else None
|
||||
blocks = _randn_with_row_padding(num_tokens, 9, hidden_size, padding=13)
|
||||
norm = 1 + torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) * 0.1
|
||||
score = torch.randn_like(norm) / hidden_size**0.5
|
||||
out_norm = 1 + torch.randn_like(norm) * 0.1
|
||||
ref_prefix, ref_blocks = prefix.clone(), blocks.clone()
|
||||
kwargs = dict(
|
||||
num_blocks=num_blocks,
|
||||
block_write_idx=num_blocks if write_block else -1,
|
||||
eps=1e-5,
|
||||
output_norm_eps=1e-5,
|
||||
)
|
||||
reference = attn_res(ref_prefix, delta, ref_blocks, norm, score, out_norm, **kwargs)
|
||||
output, scale = attn_res(
|
||||
prefix,
|
||||
delta,
|
||||
blocks,
|
||||
norm,
|
||||
score,
|
||||
out_norm,
|
||||
quant_dtype=current_platform.fp8_dtype(),
|
||||
**kwargs,
|
||||
)
|
||||
assert output.dtype == current_platform.fp8_dtype()
|
||||
assert scale.shape == (num_tokens, 1)
|
||||
if num_tokens:
|
||||
# Keep reference rounding independent of Inductor's fused quantization.
|
||||
quant = QuantFP8(
|
||||
static=False, group_shape=GroupShape.PER_TOKEN, compile_native=False
|
||||
)
|
||||
ref_output, ref_scale = quant(reference)
|
||||
torch.testing.assert_close(scale, ref_scale, atol=1e-7, rtol=1e-6)
|
||||
|
||||
# Floating-point fusion can move values at FP8 rounding midpoints.
|
||||
# Bound each change to the adjacent code and bound how often it occurs.
|
||||
# Codes are sign-magnitude, so order them by value to keep a step
|
||||
# across zero adjacent.
|
||||
def ordinal(x: torch.Tensor) -> torch.Tensor:
|
||||
code = x.view(torch.uint8).to(torch.int16)
|
||||
return torch.where(code >= 0x80, 0x80 - code, code)
|
||||
|
||||
code_delta = (ordinal(output) - ordinal(ref_output)).abs()
|
||||
assert code_delta.max().item() <= 1
|
||||
assert (code_delta != 0).float().mean().item() < 1e-4
|
||||
torch.testing.assert_close(prefix, ref_prefix, atol=0, rtol=0)
|
||||
torch.testing.assert_close(blocks, ref_blocks, atol=0, rtol=0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"matching,requires_unquantized", [(True, False), (False, False), (True, True)]
|
||||
)
|
||||
def test_mla_input_quant_requires_all_consumers(matching, requires_unquantized):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.layers.fusion.quant_activation import (
|
||||
expose_input_quant_key,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8DynamicTokenSym,
|
||||
)
|
||||
from vllm.models.kimi_k3.amd.mla import KimiK3MultiHeadLatentAttentionWrapper
|
||||
|
||||
attention = object.__new__(KimiK3MultiHeadLatentAttentionWrapper)
|
||||
nn.Module.__init__(attention)
|
||||
attention.indexer = None
|
||||
attention.q_lora_rank = 1536
|
||||
attention.fused_qkv_a_proj = nn.Identity()
|
||||
attention.g_proj = nn.Identity()
|
||||
kernel = SimpleNamespace(input_quant_key=lambda: kFp8DynamicTokenSym)
|
||||
expose_input_quant_key(attention.fused_qkv_a_proj, kernel)
|
||||
if matching:
|
||||
expose_input_quant_key(attention.g_proj, kernel)
|
||||
attention.g_proj.requires_unquantized_input = requires_unquantized
|
||||
actual = attention.get_input_quant_key()
|
||||
assert actual == (
|
||||
kFp8DynamicTokenSym if matching and not requires_unquantized else None
|
||||
)
|
||||
|
||||
@@ -75,7 +75,7 @@ def _builder(
|
||||
vllm_config.cache_config.prefix_match_unit = prefix_match_unit
|
||||
if num_spec:
|
||||
vllm_config.speculative_config = _StubSpeculativeConfig(num_spec)
|
||||
return KimiK3ROCmKDAMetadataBuilder(
|
||||
builder = KimiK3ROCmKDAMetadataBuilder(
|
||||
kv_cache_spec=MambaSpec(
|
||||
block_size=block_size,
|
||||
shapes=((16, 64),),
|
||||
@@ -91,6 +91,11 @@ def _builder(
|
||||
vllm_config=vllm_config,
|
||||
device=torch.device("cuda"),
|
||||
)
|
||||
vllm_config.cache_config.hash_block_size = prefix_match_unit or block_size
|
||||
vllm_config.cache_config.cache_hit_alignment_tokens = (
|
||||
prefix_match_unit or block_size
|
||||
)
|
||||
return builder
|
||||
|
||||
|
||||
def _build(batch: BatchSpec, block_size: int = BLOCK_SIZE, **kw):
|
||||
|
||||
@@ -22,7 +22,7 @@ from tests.utils import (
|
||||
from vllm.distributed import get_tp_group
|
||||
from vllm.model_executor.layers.fused_moe.runner import moe_runner
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear, ReplicatedLinear
|
||||
from vllm.models.kimi_k3.amd import latent_moe_runner
|
||||
from vllm.models.kimi_k3.amd.latent_moe_runner import ROCmLatentMoERunner
|
||||
from vllm.models.kimi_k3.amd.linear import KimiRoutedOutputTransform
|
||||
@@ -40,20 +40,42 @@ EPS = 1e-5
|
||||
DTYPE = torch.bfloat16
|
||||
|
||||
|
||||
def _build_transform(device: torch.device) -> KimiRoutedOutputTransform:
|
||||
def _build_transform(
|
||||
device: torch.device, *, row_sharded: bool = False
|
||||
) -> tuple[KimiRoutedOutputTransform, torch.Tensor]:
|
||||
norm = RMSNorm(LATENT_SIZE, eps=EPS).to(device=device, dtype=DTYPE)
|
||||
up_proj = ReplicatedLinear(
|
||||
LATENT_SIZE,
|
||||
HIDDEN_SIZE,
|
||||
bias=False,
|
||||
params_dtype=DTYPE,
|
||||
prefix="routed_expert_up_proj",
|
||||
).to(device=device)
|
||||
|
||||
torch.manual_seed(0)
|
||||
norm.weight.data.copy_(1 + 0.1 * torch.randn_like(norm.weight))
|
||||
up_proj.weight.data.copy_(torch.randn_like(up_proj.weight) / LATENT_SIZE**0.5)
|
||||
return KimiRoutedOutputTransform(norm, up_proj)
|
||||
full_weight = (
|
||||
torch.randn(HIDDEN_SIZE, LATENT_SIZE, device=device, dtype=DTYPE)
|
||||
/ LATENT_SIZE**0.5
|
||||
)
|
||||
|
||||
up_proj: ReplicatedLinear | ColumnParallelLinear
|
||||
if row_sharded:
|
||||
up_proj = ColumnParallelLinear(
|
||||
LATENT_SIZE,
|
||||
HIDDEN_SIZE,
|
||||
bias=False,
|
||||
gather_output=True,
|
||||
params_dtype=DTYPE,
|
||||
prefix="routed_expert_up_proj",
|
||||
).to(device=device)
|
||||
up_proj.weight_loader(up_proj.weight, full_weight)
|
||||
else:
|
||||
up_proj = ReplicatedLinear(
|
||||
LATENT_SIZE,
|
||||
HIDDEN_SIZE,
|
||||
bias=False,
|
||||
params_dtype=DTYPE,
|
||||
prefix="routed_expert_up_proj",
|
||||
).to(device=device)
|
||||
up_proj.weight.data.copy_(full_weight)
|
||||
return (
|
||||
KimiRoutedOutputTransform(norm, up_proj, row_sharded=row_sharded),
|
||||
full_weight,
|
||||
)
|
||||
|
||||
|
||||
def _tail_runner(
|
||||
@@ -72,6 +94,7 @@ def _tail_runner(
|
||||
runner = object.__new__(ROCmLatentMoERunner)
|
||||
attrs = {
|
||||
"routed_output_transform": transform,
|
||||
"_up_proj_preshard": bool(getattr(transform, "row_sharded", False)),
|
||||
"_up_proj_shard_size": HIDDEN_SIZE // tp_world,
|
||||
"_logged_sharded_tail": False,
|
||||
"moe_config": SimpleNamespace(
|
||||
@@ -101,9 +124,13 @@ def _rank_partials(
|
||||
|
||||
|
||||
def _check_matches_replicated(
|
||||
device: torch.device, tp_world: int, rank: int, use_ep: bool = False
|
||||
device: torch.device,
|
||||
tp_world: int,
|
||||
rank: int,
|
||||
use_ep: bool = False,
|
||||
row_sharded: bool = False,
|
||||
) -> None:
|
||||
transform = _build_transform(device)
|
||||
transform, up_weight = _build_transform(device, row_sharded=row_sharded)
|
||||
runner = _tail_runner(transform, tp_world, use_ep)
|
||||
group = get_tp_group().device_group
|
||||
|
||||
@@ -118,7 +145,7 @@ def _check_matches_replicated(
|
||||
transform.norm.weight,
|
||||
EPS,
|
||||
),
|
||||
transform.up_proj.weight,
|
||||
up_weight,
|
||||
)
|
||||
expected.add_(_all_reduced(shared_output, group))
|
||||
|
||||
@@ -136,12 +163,37 @@ def _check_matches_replicated_under_ep(
|
||||
_check_matches_replicated(device, tp_world, rank, use_ep=True)
|
||||
|
||||
|
||||
def _check_presharded_matches_replicated(
|
||||
device: torch.device, tp_world: int, rank: int
|
||||
) -> None:
|
||||
_check_matches_replicated(device, tp_world, rank, row_sharded=True)
|
||||
|
||||
|
||||
def _check_unfused_tail_gathers_full_hidden(
|
||||
device: torch.device, tp_world: int, rank: int
|
||||
) -> None:
|
||||
transform, up_weight = _build_transform(device, row_sharded=True)
|
||||
assert transform.up_proj.weight.shape[0] == HIDDEN_SIZE // tp_world
|
||||
|
||||
# all-gather reconstructs the full projection when all ranks feed the same
|
||||
# input, so use one seed for all ranks.
|
||||
torch.manual_seed(1234)
|
||||
latent = torch.randn(4, LATENT_SIZE, device=device, dtype=DTYPE).mul_(0.01)
|
||||
|
||||
torch.testing.assert_close(
|
||||
transform(latent),
|
||||
F.linear(transform.norm(latent), up_weight),
|
||||
atol=8e-2,
|
||||
rtol=3e-2,
|
||||
)
|
||||
|
||||
|
||||
def _check_writes_only_its_own_shard(
|
||||
device: torch.device, tp_world: int, rank: int
|
||||
) -> None:
|
||||
"""Two ranks that swapped both weight rows and write offsets still sum to
|
||||
the right total, so inspect each slice before the final collective."""
|
||||
transform = _build_transform(device)
|
||||
transform, up_weight = _build_transform(device)
|
||||
runner = _tail_runner(transform, tp_world)
|
||||
group = get_tp_group().device_group
|
||||
|
||||
@@ -169,7 +221,7 @@ def _check_writes_only_its_own_shard(
|
||||
shard = HIDDEN_SIZE // tp_world
|
||||
start, end = rank * shard, (rank + 1) * shard
|
||||
local = captured["states"]
|
||||
projected = F.linear(latent, transform.up_proj.weight[start:end])
|
||||
projected = F.linear(latent, up_weight[start:end])
|
||||
|
||||
torch.testing.assert_close(
|
||||
local[:, start:end], before[:, start:end] + projected, atol=8e-2, rtol=3e-2
|
||||
@@ -181,6 +233,8 @@ def _check_writes_only_its_own_shard(
|
||||
_CHECKS = {
|
||||
"matches_replicated": _check_matches_replicated,
|
||||
"matches_replicated_ep": _check_matches_replicated_under_ep,
|
||||
"presharded_matches_replicated": _check_presharded_matches_replicated,
|
||||
"unfused_gathers": _check_unfused_tail_gathers_full_hidden,
|
||||
"own_shard_only": _check_writes_only_its_own_shard,
|
||||
}
|
||||
|
||||
@@ -219,6 +273,16 @@ def test_sharded_tail_tp8_ep8_matches_replicated_projection() -> None:
|
||||
_run_ranks("matches_replicated_ep", 8)
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=4)
|
||||
def test_presharded_tail_tp4_matches_replicated_projection() -> None:
|
||||
_run_ranks("presharded_matches_replicated", 4)
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=4)
|
||||
def test_presharded_unfused_tail_gathers_the_full_hidden_dim() -> None:
|
||||
_run_ranks("unfused_gathers", 4)
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=4)
|
||||
def test_sharded_tail_tp4_writes_only_its_own_shard() -> None:
|
||||
_run_ranks("own_shard_only", 4)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
@@ -36,3 +39,81 @@ def test_mla_self_attention_returns_projection_storage_directly() -> None:
|
||||
|
||||
assert output is projected
|
||||
assert output.data_ptr() == projected.data_ptr()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("quantized", [False, True])
|
||||
@pytest.mark.parametrize("fused_decode", [False, True])
|
||||
def test_mla_forward_preserves_output_shape_with_fp8_input(
|
||||
monkeypatch, quantized: bool, fused_decode: bool
|
||||
) -> None:
|
||||
"""Both MLA paths accept producer-quantized input after decode fusion."""
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8DynamicTokenSym,
|
||||
)
|
||||
from vllm.models.kimi_k3.amd.mla import KimiK3MultiHeadLatentAttentionWrapper
|
||||
|
||||
hidden_states = torch.randn(4, 8, dtype=torch.bfloat16)
|
||||
if quantized:
|
||||
hidden_states = QuantizedActivation(
|
||||
hidden_states.to(kFp8DynamicTokenSym.dtype),
|
||||
torch.ones(4, 1),
|
||||
hidden_states.dtype,
|
||||
hidden_states.shape,
|
||||
kFp8DynamicTokenSym,
|
||||
)
|
||||
projected = torch.randn(4, 8, dtype=torch.bfloat16)
|
||||
paths = []
|
||||
|
||||
def input_projection(value):
|
||||
assert value is hidden_states
|
||||
return torch.zeros(4, 8, dtype=torch.bfloat16), None
|
||||
|
||||
def attention_output(path, output_shape):
|
||||
assert output_shape == projected.shape
|
||||
paths.append(path)
|
||||
return projected
|
||||
|
||||
attention = SimpleNamespace(
|
||||
q_lora_rank=2,
|
||||
kv_lora_rank=4,
|
||||
qk_rope_head_dim=2,
|
||||
qk_head_dim=4,
|
||||
num_heads=2,
|
||||
v_head_dim=4,
|
||||
fused_qkv_a_proj=input_projection,
|
||||
q_a_layernorm=nn.Identity(),
|
||||
_normalize_q_kv=lambda q, kv: (q, kv),
|
||||
q_b_proj=lambda q: (torch.zeros(4, 8, dtype=q.dtype), None),
|
||||
rotary_emb=None,
|
||||
indexer=None,
|
||||
dcp_q_replicate=False,
|
||||
_fused_qk_prep=fused_decode,
|
||||
_fused_decode=lambda q, kv, pe, pos, shape, *args: attention_output(
|
||||
"fused", shape
|
||||
),
|
||||
g_proj=None,
|
||||
o_proj=lambda value: (value, None),
|
||||
)
|
||||
if fused_decode:
|
||||
attention.mla_attn = SimpleNamespace(layer_name="test")
|
||||
monkeypatch.setattr(
|
||||
"vllm.models.kimi_k3.amd.mla.get_attention_context",
|
||||
lambda _: (
|
||||
SimpleNamespace(num_actual_tokens=4, num_decode_tokens=4),
|
||||
None,
|
||||
torch.zeros(1),
|
||||
torch.arange(4),
|
||||
),
|
||||
)
|
||||
else:
|
||||
attention.mla_attn = lambda q, kv, pe, **kwargs: attention_output(
|
||||
"regular", kwargs["output_shape"]
|
||||
)
|
||||
|
||||
output = KimiK3MultiHeadLatentAttentionWrapper.forward(
|
||||
attention, torch.arange(4), hidden_states
|
||||
)
|
||||
|
||||
assert output is projected
|
||||
assert paths == ["fused" if fused_decode else "regular"]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -91,9 +91,7 @@ def test_int4_per_group_32_is_not_an_online_moe_method():
|
||||
QuantizationConfigArgs(moe={"weight": "int4_per_group_32"})
|
||||
)
|
||||
assert (
|
||||
config.resolve_quant_method_cls(
|
||||
Mock(spec=RoutedExperts), "model.layers.0.mlp.experts"
|
||||
)
|
||||
config.resolve_quant_method_cls(RoutedExperts, "model.layers.0.mlp.experts")
|
||||
is None
|
||||
)
|
||||
|
||||
@@ -103,6 +101,4 @@ def test_unknown_online_moe_weight_still_raises():
|
||||
QuantizationConfigArgs(moe={"weight": "fp8_per_token"})
|
||||
)
|
||||
with pytest.raises(ValueError, match="online quantization"):
|
||||
config.resolve_quant_method_cls(
|
||||
Mock(spec=RoutedExperts), "model.layers.0.mlp.experts"
|
||||
)
|
||||
config.resolve_quant_method_cls(RoutedExperts, "model.layers.0.mlp.experts")
|
||||
|
||||
@@ -100,6 +100,8 @@ def _make_builder(
|
||||
prefix_match_unit: int | None = None,
|
||||
use_eagle: bool = False,
|
||||
disable_eagle_block_drop: bool = False,
|
||||
cache_hit_alignment_tokens: int | None = None,
|
||||
hash_block_size: int | None = None,
|
||||
) -> AttentionMetadataBuilder:
|
||||
vllm_config = create_vllm_config(
|
||||
model_name="Qwen/Qwen3.5-0.8B",
|
||||
@@ -122,6 +124,11 @@ def _make_builder(
|
||||
vllm_config.cache_config.use_replayssm = use_recoverssm
|
||||
vllm_config.cache_config.use_recoverssm = use_recoverssm
|
||||
vllm_config.cache_config.prefix_match_unit = prefix_match_unit
|
||||
hash_block_size = hash_block_size or prefix_match_unit or mamba_block_size
|
||||
vllm_config.cache_config.hash_block_size = hash_block_size
|
||||
vllm_config.cache_config.cache_hit_alignment_tokens = (
|
||||
cache_hit_alignment_tokens or hash_block_size
|
||||
)
|
||||
builder = builder_cls(
|
||||
kv_cache_spec=MambaSpec(
|
||||
block_size=mamba_block_size,
|
||||
@@ -220,6 +227,8 @@ def test_kda_recoverssm_startup_metadata_flow_without_model(monkeypatch):
|
||||
vllm_config=builder_config,
|
||||
device=DEVICE,
|
||||
)
|
||||
builder_config.cache_config.hash_block_size = BLOCK_SIZE
|
||||
builder_config.cache_config.cache_hit_alignment_tokens = BLOCK_SIZE
|
||||
|
||||
# An all-prefill speculative batch used to leave an all-false spec mask
|
||||
# alive, then access active_non_spec_mask_cpu before it was initialized.
|
||||
@@ -287,18 +296,45 @@ def test_kda_recoverssm_startup_metadata_flow_without_model(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_internal_checkpoint_metadata_targets_last_aligned_boundary():
|
||||
@pytest.mark.parametrize(
|
||||
"batch,prefix_match_unit,hit_alignment,expected_offsets,expected_states",
|
||||
[
|
||||
(
|
||||
BatchSpec(seq_lens=[50, 32], query_lens=[50, 16]),
|
||||
None,
|
||||
16,
|
||||
[48, 0],
|
||||
[2, NULL_BLOCK_ID],
|
||||
),
|
||||
(
|
||||
BatchSpec(seq_lens=[50, 32], query_lens=[50, 16]),
|
||||
16,
|
||||
16,
|
||||
[48, 0],
|
||||
[2, NULL_BLOCK_ID],
|
||||
),
|
||||
(BatchSpec(seq_lens=[530], query_lens=[530]), None, 128, [512], [32]),
|
||||
(BatchSpec(seq_lens=[530], query_lens=[50]), None, 128, [32], [32]),
|
||||
(BatchSpec(seq_lens=[530], query_lens=[530]), 16, 16, [528], [32]),
|
||||
(BatchSpec(seq_lens=[530], query_lens=[50]), 16, 16, [48], [32]),
|
||||
],
|
||||
)
|
||||
def test_internal_checkpoint_metadata_targets_last_aligned_boundary(
|
||||
batch, prefix_match_unit, hit_alignment, expected_offsets, expected_states
|
||||
):
|
||||
device = torch.device("cuda")
|
||||
batch = BatchSpec(seq_lens=[50, 32], query_lens=[50, 16])
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
batch, BLOCK_SIZE, device, arange_block_indices=True
|
||||
).replace(is_prefilling=torch.tensor([True, True]))
|
||||
).replace(is_prefilling=torch.tensor([True] * len(batch.seq_lens)))
|
||||
builder = _make_builder(
|
||||
KimiK3KDAMetadataBuilder,
|
||||
num_speculative_tokens=0,
|
||||
full_cuda_graph=False,
|
||||
mamba_cache_mode="align",
|
||||
num_prefill_checkpoint_blocks=1,
|
||||
prefix_match_unit=prefix_match_unit,
|
||||
cache_hit_alignment_tokens=hit_alignment,
|
||||
hash_block_size=16,
|
||||
device=device,
|
||||
)
|
||||
assert isinstance(builder, KimiK3KDAMetadataBuilder)
|
||||
@@ -313,26 +349,33 @@ def test_internal_checkpoint_metadata_targets_last_aligned_boundary():
|
||||
assert actual.checkpoint is not None
|
||||
torch.testing.assert_close(
|
||||
actual.checkpoint.state_indices,
|
||||
torch.tensor([2, NULL_BLOCK_ID], dtype=torch.int32, device=device),
|
||||
torch.tensor(expected_states, dtype=torch.int32, device=device),
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
actual.checkpoint.checkpoint_offsets,
|
||||
torch.tensor([48, 0], dtype=torch.int32, device=device),
|
||||
torch.tensor(expected_offsets, dtype=torch.int32, device=device),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("disable_eagle_block_drop", "prefix_match_unit", "expected_offset"),
|
||||
[(False, 16, 80), (True, 16, 96), (False, 8, None)],
|
||||
("seq_len", "disable_eagle_block_drop", "prefix_match_unit", "expected_offset"),
|
||||
[
|
||||
(100, False, 16, 80),
|
||||
(100, True, 16, 96),
|
||||
(100, False, 8, None),
|
||||
(96, False, 16, 80),
|
||||
(96, True, 16, 80),
|
||||
],
|
||||
)
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_spec_internal_checkpoint_metadata_targets_replay_boundary(
|
||||
seq_len: int,
|
||||
disable_eagle_block_drop: bool,
|
||||
prefix_match_unit: int,
|
||||
expected_offset: int | None,
|
||||
) -> None:
|
||||
device = torch.device("cuda")
|
||||
batch = BatchSpec(seq_lens=[100], query_lens=[100])
|
||||
batch = BatchSpec(seq_lens=[seq_len], query_lens=[seq_len])
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
batch, BLOCK_SIZE, device, arange_block_indices=True
|
||||
)
|
||||
@@ -390,6 +433,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
|
||||
full_cuda_graph=False,
|
||||
mamba_cache_mode="align",
|
||||
num_prefill_checkpoint_blocks=1,
|
||||
prefix_match_unit=16,
|
||||
device=device,
|
||||
)
|
||||
assert isinstance(builder, KimiK3KDAMetadataBuilder)
|
||||
@@ -447,7 +491,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
|
||||
2,
|
||||
False,
|
||||
[False, False],
|
||||
None,
|
||||
1,
|
||||
id="no-scheduled-draft-tokens",
|
||||
),
|
||||
pytest.param(
|
||||
|
||||
@@ -13,8 +13,10 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.model_executor.layers.attention.mla_attention as mla_attention
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonBaseImpl,
|
||||
MLACommonImpl,
|
||||
MLACommonPrefillMetadata,
|
||||
build_mla_chunked_context_metadata,
|
||||
)
|
||||
@@ -317,3 +319,115 @@ def test_fused_context_rejects_an_unquantized_query() -> None:
|
||||
)
|
||||
with pytest.raises(AssertionError, match="new-token epilogue"):
|
||||
layer._compute_prefill_context(q, SimpleNamespace(prefill=prefill))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Decode context parallelism: the generic impl keeps its loop (allgather +
|
||||
# reorg) and only the per-chunk K/V pack is handed to the layer's fused kernel.
|
||||
# --------------------------------------------------------------------------
|
||||
_DCP = 2
|
||||
_DCP_TOKENS = 48
|
||||
|
||||
|
||||
def _run_dcp_context_loop(monkeypatch, *, q_data_type, fused_mla_kv_concat_fn):
|
||||
"""Drive ``MLACommonImpl._context_parallel_compute_prefill_context`` on one
|
||||
chunk with the collective pieces (gather, allgather, reorg) stubbed out."""
|
||||
torch.manual_seed(0)
|
||||
device = torch.device("cuda")
|
||||
kv_b_proj = _KVBProj(device, weight_dtype=torch.bfloat16)
|
||||
workspace = torch.randn(
|
||||
(_DCP_TOKENS * (_DCP + 1), _ENTRY), dtype=torch.bfloat16, device=device
|
||||
)
|
||||
impl = SimpleNamespace(
|
||||
kv_cache_dtype="auto",
|
||||
kv_lora_rank=_KV_LORA_RANK,
|
||||
qk_rope_head_dim=_QK_ROPE,
|
||||
qk_nope_head_dim=_QK_NOPE,
|
||||
v_head_dim=_V_HEAD_DIM,
|
||||
num_heads=_NUM_HEADS,
|
||||
kv_b_proj=kv_b_proj,
|
||||
_use_flashinfer_concat_mla_k=False,
|
||||
)
|
||||
impl._concat_k_nope_k_pe = MLACommonImpl._concat_k_nope_k_pe.__get__(impl)
|
||||
|
||||
monkeypatch.setattr(mla_attention.ops, "cp_gather_cache", lambda **_: None)
|
||||
monkeypatch.setattr(mla_attention, "_get_kv_b_proj_input_dtype", lambda *_: None)
|
||||
monkeypatch.setattr(
|
||||
mla_attention,
|
||||
"reorg_kvcache",
|
||||
lambda kv_c, k_pe, **_: (kv_c[:_DCP_TOKENS].squeeze(1), k_pe[:_DCP_TOKENS]),
|
||||
)
|
||||
chunk = SimpleNamespace(
|
||||
index=0,
|
||||
padded_local_seq_lens=[_DCP_TOKENS],
|
||||
local_context_lens_allranks=[[_DCP_TOKENS // _DCP] * _DCP],
|
||||
padded_local_cu_seq_lens=torch.tensor([0, _DCP_TOKENS], device=device),
|
||||
padded_local_token_to_seq=torch.zeros(
|
||||
_DCP_TOKENS, dtype=torch.int32, device=device
|
||||
),
|
||||
local_starts=[0],
|
||||
num_local_context_tokens=_DCP_TOKENS,
|
||||
request_slice=slice(0, 1),
|
||||
num_requests=1,
|
||||
starts=torch.tensor([0], device=device),
|
||||
num_context_tokens=_DCP_TOKENS,
|
||||
max_seq_len=_DCP_TOKENS,
|
||||
token_slice=slice(0, 4),
|
||||
)
|
||||
backend = _RecordingPrefillBackend()
|
||||
attn_metadata = SimpleNamespace(
|
||||
prefill=SimpleNamespace(
|
||||
prefill_backend=backend,
|
||||
chunked_context=SimpleNamespace(
|
||||
workspace=workspace,
|
||||
chunks=[chunk],
|
||||
empty_token_slices=False,
|
||||
dcp_manager=SimpleNamespace(kv_gather=lambda dst, src: None),
|
||||
),
|
||||
q_data_type=q_data_type,
|
||||
block_table=torch.zeros((1, 1), dtype=torch.int32, device=device),
|
||||
)
|
||||
)
|
||||
q = torch.randn(
|
||||
(4, _NUM_HEADS, _QK_NOPE + _QK_ROPE), dtype=torch.bfloat16, device=device
|
||||
)
|
||||
out, lse = MLACommonImpl._context_parallel_compute_prefill_context(
|
||||
impl,
|
||||
q,
|
||||
torch.empty(0, device=device),
|
||||
attn_metadata,
|
||||
k_scale=torch.ones(1, device=device),
|
||||
dcp_world_size=_DCP,
|
||||
fused_mla_kv_concat_fn=fused_mla_kv_concat_fn,
|
||||
)
|
||||
return backend, out, lse
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
|
||||
@torch.inference_mode()
|
||||
def test_dcp_context_fused_pack_matches_generic_tail(
|
||||
monkeypatch, kv_cache_dtype: str
|
||||
) -> None:
|
||||
"""Under DCP the layer's fused K/V pack must feed the prefill backend exactly
|
||||
what the generic impl's cast + split + concat tail feeds it."""
|
||||
q_data_type = (
|
||||
current_platform.fp8_dtype() if kv_cache_dtype == "fp8" else torch.bfloat16
|
||||
)
|
||||
layer = SimpleNamespace(qk_nope_head_dim=_QK_NOPE, v_head_dim=_V_HEAD_DIM)
|
||||
fused_fn = MultiHeadLatentAttention._fused_mla_kv_concat.__get__(layer)
|
||||
|
||||
backend_ref, ref_out, ref_lse = _run_dcp_context_loop(
|
||||
monkeypatch, q_data_type=q_data_type, fused_mla_kv_concat_fn=None
|
||||
)
|
||||
backend_fused, fused_out, fused_lse = _run_dcp_context_loop(
|
||||
monkeypatch, q_data_type=q_data_type, fused_mla_kv_concat_fn=fused_fn
|
||||
)
|
||||
assert len(backend_ref.calls) == len(backend_fused.calls) == 1
|
||||
for name, fused_t, ref_t in zip(
|
||||
("q", "k", "v"), backend_fused.calls[0], backend_ref.calls[0], strict=True
|
||||
):
|
||||
torch.testing.assert_close(
|
||||
fused_t, ref_t, atol=0, rtol=0, msg=lambda m, n=name: f"{n} differs: {m}"
|
||||
)
|
||||
torch.testing.assert_close(fused_out, ref_out, atol=0, rtol=0)
|
||||
torch.testing.assert_close(fused_lse, ref_lse, atol=0, rtol=0)
|
||||
|
||||
@@ -8,6 +8,7 @@ import random
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
from math import lcm
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
@@ -353,6 +354,45 @@ def _format(turns: list[Turn]) -> str:
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"prompt_len",
|
||||
[
|
||||
# Blocks=6144, PMU=128. P=7040 is PMU-aligned but not block-aligned:
|
||||
# ensure lookup reads the cached attention proof at 7040 despite
|
||||
# the final hit limit of 7039, then applies EAGLE's 128-token drop.
|
||||
pytest.param(7040, id="eagle-proof-scan"),
|
||||
# Blocks=6144, PMU=128. P=7296 is an exact PMU multiple:
|
||||
# ensure the Mamba checkpoint is 7168, not 7040 from applying both
|
||||
# the P - 1 cap and EAGLE's 128-token drop.
|
||||
pytest.param(7296, id="eagle-double-cap"),
|
||||
],
|
||||
)
|
||||
def test_dspark_exact_resend_reuses_prompt_checkpoint(prompt_len: int) -> None:
|
||||
"""Resends reuse the Mamba checkpoint and its companion EAGLE attention proof."""
|
||||
mode = Mode(128, True)
|
||||
salt = str(uuid4())
|
||||
rng = random.Random(0)
|
||||
prompt = [rng.randint(1000, 150000) for _ in range(prompt_len)]
|
||||
deployment = DEPLOYMENTS["plain"]
|
||||
with _serve(deployment, mode) as servers:
|
||||
url = servers[0].url_root
|
||||
cold = _complete(url, prompt, salt, max_tokens=1)
|
||||
resend = _complete(url, prompt, salt, max_tokens=1)
|
||||
recompute = _complete(url, prompt, f"{salt}-recompute", max_tokens=1)
|
||||
|
||||
# EAGLE's dropped hash unit already leaves tokens to recompute on resend.
|
||||
expected = (prompt_len // 128 - 1) * 128
|
||||
actual = _cached(resend)
|
||||
assert _cached(cold) == _cached(recompute) == 0
|
||||
assert actual == expected, f"{prompt_len=}: {actual=}, {expected=}"
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=[_tokens_text_logprobs(recompute)],
|
||||
outputs_1_lst=[_tokens_text_logprobs(resend)],
|
||||
name_0="recompute",
|
||||
name_1="resend",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name, mode", [_case(name, mode) for name in DEPLOYMENTS for mode in MODES]
|
||||
)
|
||||
|
||||
@@ -301,6 +301,27 @@ def test_shard_sequence_parallel_mlp_gating(
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("moe_backend", "all2all_backend", "expected"),
|
||||
[
|
||||
("deep_gemm_mega_moe", "naive", True),
|
||||
("auto", "deepep_v2", True),
|
||||
("auto", "deepep_low_latency", False),
|
||||
],
|
||||
)
|
||||
def test_shared_expert_sharding_backend_gate(
|
||||
moe_backend: str,
|
||||
all2all_backend: str,
|
||||
expected: bool,
|
||||
):
|
||||
vllm_config = SimpleNamespace(
|
||||
kernel_config=SimpleNamespace(moe_backend=moe_backend),
|
||||
parallel_config=SimpleNamespace(all2all_backend=all2all_backend),
|
||||
)
|
||||
|
||||
assert kimi_model.can_shard_sequence_parallel_shared_expert(vllm_config) is expected
|
||||
|
||||
|
||||
def test_sharded_sequence_parallel_mlp_matches_replicated(default_vllm_config):
|
||||
"""Sharded SP MLP must reproduce the replicated result for every token.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user