[Mini-vLLM] SM86-only cut: models, backends, Rust, tests
- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries - Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels - Remove inc/quark quant loaders; keep compressed-tensors and Marlin - Drop the Rust frontend, pooling entrypoints, and idle test suites - Rebuild kernels for sm_80;sm_86 and strip the extensions - Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,157 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.qwen4_exp.nvidia.ops.cute_dsl.hc_down_silu import hc_down_silu
|
||||
from vllm.models.qwen4_exp.nvidia.ops.hc import (
|
||||
grouped_gemma_rmsnorm,
|
||||
hc_combine,
|
||||
hc_combine_norm,
|
||||
hc_gate_mix,
|
||||
hc_silu,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda() or not HAS_TRITON,
|
||||
reason="HC kernels require CUDA and Triton",
|
||||
)
|
||||
|
||||
HC = 4
|
||||
HIDDEN_SIZE = 2560
|
||||
HYPER_HIDDEN_SIZE = HC * HIDDEN_SIZE
|
||||
EPS = 1e-6
|
||||
LORA_RANK = 320
|
||||
DOWN_N = LORA_RANK + HC + 12 # merged down+inject weight, 16-row padded
|
||||
|
||||
requires_sm90 = pytest.mark.skipif(
|
||||
not current_platform.has_device_capability(90),
|
||||
reason="fused HC down+SiLU requires SM90+",
|
||||
)
|
||||
|
||||
|
||||
def test_grouped_gemma_rmsnorm() -> None:
|
||||
torch.manual_seed(0)
|
||||
x = torch.randn(2, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
weight = torch.randn(HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
|
||||
actual = grouped_gemma_rmsnorm(x, weight, EPS, HC)
|
||||
|
||||
grouped = x.float().unflatten(-1, (HC, HIDDEN_SIZE))
|
||||
variance = grouped.square().mean(-1, keepdim=True)
|
||||
expected = grouped * torch.rsqrt(variance + EPS)
|
||||
expected = expected.flatten(-2) * (1.0 + weight.float())
|
||||
torch.testing.assert_close(actual, expected.to(torch.bfloat16))
|
||||
|
||||
|
||||
def test_hc_gate_mix() -> None:
|
||||
torch.manual_seed(0)
|
||||
x = torch.randn(2, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
gate = torch.randn(2, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
|
||||
actual = hc_gate_mix(x, gate, HC)
|
||||
expected = (
|
||||
torch.sigmoid(gate.float().unflatten(-1, (HC, HIDDEN_SIZE)))
|
||||
* x.float().unflatten(-1, (HC, HIDDEN_SIZE))
|
||||
).mean(-2)
|
||||
|
||||
torch.testing.assert_close(actual, expected.to(torch.bfloat16))
|
||||
|
||||
|
||||
def test_hc_combine() -> None:
|
||||
torch.manual_seed(0)
|
||||
block_output = torch.randn(2, HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
residual = torch.randn(2, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
injection = torch.randn(2, HC, dtype=torch.bfloat16, device="cuda")
|
||||
|
||||
actual = hc_combine(residual, block_output, injection, HC)
|
||||
injection_weight = 2.0 * torch.sigmoid(injection.float() / HC)
|
||||
expected = residual.float().unflatten(-1, (HC, HIDDEN_SIZE))
|
||||
expected = expected + block_output.float().unsqueeze(
|
||||
-2
|
||||
) * injection_weight.unsqueeze(-1)
|
||||
|
||||
torch.testing.assert_close(actual, expected.flatten(-2).to(torch.bfloat16))
|
||||
|
||||
|
||||
def test_hc_combine_unit_injection() -> None:
|
||||
torch.manual_seed(0)
|
||||
block_output = torch.randn(2, HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
residual = torch.randn(2, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
|
||||
actual = hc_combine(residual, block_output, None, HC)
|
||||
expected = residual.unflatten(-1, (HC, HIDDEN_SIZE))
|
||||
expected = expected + block_output.unsqueeze(-2)
|
||||
|
||||
assert torch.equal(actual, expected.flatten(-2))
|
||||
|
||||
|
||||
def test_hc_combine_norm() -> None:
|
||||
torch.manual_seed(0)
|
||||
block_output = torch.randn(2, HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
residual = torch.randn(2, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
injection = torch.randn(2, HC, dtype=torch.bfloat16, device="cuda")
|
||||
weight = torch.randn(HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
|
||||
actual, actual_norm = hc_combine_norm(
|
||||
residual, block_output, injection, weight, EPS, HC
|
||||
)
|
||||
|
||||
injection_weight = 2.0 * torch.sigmoid(injection.float() / HC)
|
||||
expected = residual.float().unflatten(-1, (HC, HIDDEN_SIZE))
|
||||
expected = expected + block_output.float().unsqueeze(
|
||||
-2
|
||||
) * injection_weight.unsqueeze(-1)
|
||||
expected = expected.flatten(-2).to(residual.dtype)
|
||||
grouped = expected.float().unflatten(-1, (HC, HIDDEN_SIZE))
|
||||
variance = grouped.square().mean(-1, keepdim=True)
|
||||
expected_norm = grouped * torch.rsqrt(variance + EPS)
|
||||
expected_norm = expected_norm.flatten(-2) * (1.0 + weight.float())
|
||||
|
||||
torch.testing.assert_close(actual, expected)
|
||||
torch.testing.assert_close(actual_norm, expected_norm.to(torch.bfloat16))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_tokens", [1, 17, 2048])
|
||||
def test_hc_combine_norm_unit_injection(num_tokens: int) -> None:
|
||||
torch.manual_seed(0)
|
||||
embedding = torch.randn(
|
||||
num_tokens, HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda"
|
||||
)
|
||||
hidden = torch.randn(
|
||||
num_tokens, HC, HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda"
|
||||
)
|
||||
weight = torch.randn(HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
|
||||
actual, actual_norm = hc_combine_norm(
|
||||
hidden.flatten(1), embedding, None, weight, EPS, HC
|
||||
)
|
||||
|
||||
expected = (hidden + embedding.unsqueeze(1)).flatten(1)
|
||||
expected_norm = grouped_gemma_rmsnorm(expected, weight, EPS, HC)
|
||||
assert torch.equal(actual, expected)
|
||||
torch.testing.assert_close(actual_norm, expected_norm)
|
||||
|
||||
|
||||
@requires_sm90
|
||||
@pytest.mark.parametrize("num_tokens", [1, 3, 5, 17, 48])
|
||||
def test_hc_down_silu_fused(num_tokens: int) -> None:
|
||||
# Compare computed columns with the unfused ll_bf16 + hc_silu reference.
|
||||
from vllm.model_executor.kernels.linear.cute_dsl.ll_bf16 import ll_bf16_gemm
|
||||
|
||||
torch.manual_seed(0)
|
||||
x = torch.randn(num_tokens, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
weight = torch.randn(DOWN_N, HYPER_HIDDEN_SIZE, dtype=torch.bfloat16, device="cuda")
|
||||
|
||||
lora, injection = hc_down_silu(x, weight, LORA_RANK, HC)
|
||||
|
||||
down = ll_bf16_gemm(x, weight).to(torch.bfloat16)
|
||||
torch.testing.assert_close(
|
||||
lora, hc_silu(down[:, :LORA_RANK], HC), rtol=0.01, atol=0.01
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
injection, down[:, LORA_RANK : LORA_RANK + HC], rtol=0.01, atol=0.01
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,493 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import inspect
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.models.qwen4_exp.amd import indexer_qsa
|
||||
from vllm.models.qwen4_exp.amd import (
|
||||
model as _qwen4_exp_model, # noqa: F401
|
||||
)
|
||||
from vllm.models.qwen4_exp.amd import ple_layer as ple_layer_module
|
||||
from vllm.models.qwen4_exp.amd.indexer_qsa import (
|
||||
QSAIndexer,
|
||||
apply_qsa_rmsnorm,
|
||||
apply_qsa_rope,
|
||||
)
|
||||
from vllm.models.qwen4_exp.amd.ops import qsa as qsa_ops
|
||||
from vllm.models.qwen4_exp.amd.ops.qsa_prepare import (
|
||||
qsa_prepare,
|
||||
supports_fused_pre_indexer,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_rocm(),
|
||||
reason="AMD QSA requires ROCm",
|
||||
)
|
||||
|
||||
requires_qsa_kernels = pytest.mark.skipif(
|
||||
not HAS_TRITON,
|
||||
reason="AMD QSA kernels require Triton",
|
||||
)
|
||||
|
||||
|
||||
def test_ple_ngram_embedding_custom_op_uses_resident_weight(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
layer_name = "model.layers.0.ple"
|
||||
layer = ple_layer_module.Qwen4ExpPLELayer.__new__(ple_layer_module.Qwen4ExpPLELayer)
|
||||
torch.nn.Module.__init__(layer)
|
||||
layer.ple_embedding = torch.nn.Module()
|
||||
layer.ple_embedding.ngram_embedding = torch.nn.Embedding(8, 3)
|
||||
context = SimpleNamespace(no_compile_layers={layer_name: layer})
|
||||
monkeypatch.setattr(ple_layer_module, "get_forward_context", lambda: context)
|
||||
|
||||
ngram_ids = torch.tensor([[0, 1], [2, 3]])
|
||||
output = torch.empty(2, 6)
|
||||
ple_layer_module.qwen4_exp_amd_ple_ngram_embedding(
|
||||
ngram_ids,
|
||||
output,
|
||||
layer_name,
|
||||
)
|
||||
|
||||
expected = layer.ple_embedding.ngram_embedding(ngram_ids).flatten(-2)
|
||||
torch.testing.assert_close(output, expected)
|
||||
|
||||
|
||||
def _qsa_sparse_paged_attention_reference(
|
||||
q: torch.Tensor,
|
||||
k_cache: torch.Tensor,
|
||||
v_cache: torch.Tensor,
|
||||
logical_indices: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
softmax_scale: float,
|
||||
) -> torch.Tensor:
|
||||
output = torch.zeros_like(q)
|
||||
repeats = q.shape[1] // k_cache.shape[2]
|
||||
page_size = k_cache.shape[1]
|
||||
for row in range(q.shape[0]):
|
||||
logical = logical_indices[row]
|
||||
logical = logical[logical >= 0].long()
|
||||
if not logical.numel():
|
||||
continue
|
||||
request = token_to_req[row].long()
|
||||
pages = block_table[request, logical // page_size].long()
|
||||
offsets = logical % page_size
|
||||
keys = k_cache[pages, offsets].repeat_interleave(repeats, dim=1)
|
||||
values = v_cache[pages, offsets].repeat_interleave(repeats, dim=1)
|
||||
scores = torch.einsum("hd,khd->hk", q[row].float(), keys.float())
|
||||
probabilities = torch.softmax(scores * softmax_scale, dim=-1)
|
||||
output[row] = torch.einsum("hk,khd->hd", probabilities, values.float()).to(
|
||||
q.dtype
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def test_qsa_rope_uses_platform_dispatch() -> None:
|
||||
tensor = torch.arange(16, dtype=torch.float32).reshape(2, 2, 4)
|
||||
positions = torch.tensor([0, 1])
|
||||
calls = []
|
||||
|
||||
def apply_rotary_emb(
|
||||
rotary_input: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
calls.append((rotary_input, cos, sin))
|
||||
return rotary_input + 1
|
||||
|
||||
rotary_emb = SimpleNamespace(
|
||||
rotary_dim=2,
|
||||
apply_rotary_emb=apply_rotary_emb,
|
||||
_match_cos_sin_cache_dtype=lambda _: torch.zeros(2, 4),
|
||||
)
|
||||
|
||||
output = apply_qsa_rope(rotary_emb, positions, tensor)
|
||||
|
||||
assert len(calls) == 1
|
||||
torch.testing.assert_close(output[..., :2], tensor[..., :2] + 1)
|
||||
torch.testing.assert_close(output[..., 2:], tensor[..., 2:])
|
||||
|
||||
|
||||
def test_qsa_rmsnorm_uses_portable_implementation(default_vllm_config) -> None:
|
||||
norm = GemmaRMSNorm(4, eps=1e-6)
|
||||
norm.weight.data.copy_(torch.tensor([0.1, -0.2, 0.3, -0.4]))
|
||||
tensor = torch.arange(8, dtype=torch.float32).reshape(2, 4)
|
||||
output = apply_qsa_rmsnorm(norm, tensor)
|
||||
|
||||
torch.testing.assert_close(output, norm.forward_native(tensor))
|
||||
|
||||
|
||||
def _make_attn(*, use_fused: bool) -> SimpleNamespace:
|
||||
"""The main-attention fields the fused QSA prepare reads from its owner."""
|
||||
return SimpleNamespace(
|
||||
use_fused_qsa_prepare=use_fused,
|
||||
kv_cache=torch.zeros(1, 2, 16, 8),
|
||||
q_norm=GemmaRMSNorm(4, eps=1e-6),
|
||||
k_norm=GemmaRMSNorm(4, eps=1e-6),
|
||||
_k_scale_float=1.0,
|
||||
_v_scale_float=1.0,
|
||||
)
|
||||
|
||||
|
||||
def _make_indexer(*, use_fused: bool, num_tokens: int = 2) -> QSAIndexer:
|
||||
"""A QSAIndexer whose unfused path runs for real, with no projection weights.
|
||||
|
||||
Both branches have to be reachable: a fused-path test is only meaningful if
|
||||
the unfused one it replaces would otherwise have executed.
|
||||
"""
|
||||
heads, head_dim = 2, 4
|
||||
indexer = QSAIndexer.__new__(QSAIndexer)
|
||||
torch.nn.Module.__init__(indexer)
|
||||
indexer.index_n_heads = heads
|
||||
indexer.index_kv_heads = 1
|
||||
indexer.index_head_dim = head_dim
|
||||
indexer.compress_ratio = 2
|
||||
indexer.use_fused_pre_indexer = use_fused
|
||||
indexer.skip_topk = True
|
||||
indexer.index_qk_proj = lambda hidden_states: (
|
||||
torch.zeros(hidden_states.shape[0], (heads + 1) * head_dim),
|
||||
None,
|
||||
)
|
||||
indexer.q_layernorm = GemmaRMSNorm(head_dim, eps=1e-6)
|
||||
indexer.k_layernorm = GemmaRMSNorm(head_dim, eps=1e-6)
|
||||
indexer.rotary_emb = SimpleNamespace(
|
||||
cos_sin_cache=torch.zeros(16, head_dim),
|
||||
rotary_dim=head_dim // 2,
|
||||
apply_rotary_emb=lambda tensor, cos, sin: tensor,
|
||||
_match_cos_sin_cache_dtype=lambda _: torch.zeros(16, head_dim),
|
||||
)
|
||||
# The raw cache's full width carries the MRoPE position tail that the fused
|
||||
# kernel writes; key_cache is only the leading key columns.
|
||||
indexer.raw_key_cache = SimpleNamespace(
|
||||
kv_cache=torch.zeros(1, 4, 1, head_dim + 12),
|
||||
key_cache=torch.zeros(1, 4, 1, head_dim),
|
||||
cache_rope_positions=True,
|
||||
rope_position_offset=head_dim,
|
||||
)
|
||||
indexer.compressed_key_cache = SimpleNamespace(
|
||||
kv_cache=torch.zeros(1, 2, 1, head_dim)
|
||||
)
|
||||
raw_metadata = SimpleNamespace(
|
||||
num_actual_tokens=num_tokens,
|
||||
slot_mapping=torch.arange(num_tokens),
|
||||
block_table=torch.zeros(1, 1, dtype=torch.int32),
|
||||
query_start_loc=torch.tensor([0, num_tokens], dtype=torch.int32),
|
||||
logical_positions=torch.arange(num_tokens),
|
||||
token_to_req=torch.zeros(num_tokens, dtype=torch.int32),
|
||||
)
|
||||
compressed_metadata = SimpleNamespace(
|
||||
num_actual_tokens=num_tokens,
|
||||
slot_mapping=torch.arange(num_tokens),
|
||||
k_work_metadata=torch.zeros(1, 2, dtype=torch.int32),
|
||||
)
|
||||
indexer._metadata = lambda: (raw_metadata, compressed_metadata)
|
||||
indexer.test_metadata = (raw_metadata, compressed_metadata)
|
||||
return indexer
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("default_vllm_config")
|
||||
def test_qsa_fused_prepare_replaces_the_unfused_chain(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
indexer = _make_indexer(use_fused=True)
|
||||
attn = _make_attn(use_fused=True)
|
||||
calls = []
|
||||
main_outputs = (torch.empty(0), torch.empty(0))
|
||||
|
||||
def fake_prepare(*args, **kwargs):
|
||||
calls.append((args, kwargs))
|
||||
return main_outputs
|
||||
|
||||
monkeypatch.setattr(indexer_qsa, "qsa_prepare", fake_prepare)
|
||||
monkeypatch.setattr(
|
||||
QSAIndexer,
|
||||
"_update_and_compress",
|
||||
lambda *args, **kwargs: pytest.fail("fused path ran the unfused chain"),
|
||||
)
|
||||
rows = torch.tensor([[3, 1, -1], [5, 2, 0]], dtype=torch.int32)
|
||||
qkv = torch.zeros(4, 16)
|
||||
slot_mapping = torch.arange(4)
|
||||
gate_out = torch.empty(4, 1, 4)
|
||||
|
||||
actual, actual_main = QSAIndexer.forward(
|
||||
indexer,
|
||||
torch.zeros(2, 8),
|
||||
torch.tensor([7, 8]),
|
||||
rows,
|
||||
attn=attn,
|
||||
qkv=qkv,
|
||||
slot_mapping=slot_mapping,
|
||||
gate_out=gate_out,
|
||||
)
|
||||
|
||||
assert actual is rows
|
||||
assert actual_main is main_outputs
|
||||
assert len(calls) == 1
|
||||
args, kwargs = calls[0]
|
||||
passed = inspect.signature(qsa_prepare).bind(*args, **kwargs).arguments
|
||||
_, compressed_metadata = indexer.test_metadata
|
||||
# The kernel addresses the raw cache at its full width and writes the MRoPE
|
||||
# position tail itself, so it needs kv_cache, not the key_cache view.
|
||||
assert passed["state_cache"] is indexer.raw_key_cache.kv_cache
|
||||
assert passed["compressed_cache"] is indexer.compressed_key_cache.kv_cache
|
||||
assert passed["k_work_metadata"] is compressed_metadata.k_work_metadata
|
||||
assert passed["compress_ratio"] == indexer.compress_ratio
|
||||
assert passed["rope_pos_offset"] == indexer.index_head_dim
|
||||
# Main attention: only the real tokens, the vLLM cache viewed per token,
|
||||
# and the gate landing in the caller's buffer.
|
||||
assert passed["main_qkv"].shape[0] == 2
|
||||
assert passed["main_qkv"].data_ptr() == qkv.data_ptr()
|
||||
assert passed["main_slot_mapping"].shape == (2,)
|
||||
assert passed["main_kv_cache"].shape == (1, 16, 2, 8)
|
||||
assert passed["main_kv_cache"].data_ptr() == attn.kv_cache.data_ptr()
|
||||
assert passed["main_gate_out"].shape[0] == 2
|
||||
assert passed["main_gate_out"].data_ptr() == gate_out.data_ptr()
|
||||
assert passed["main_q_norm_weight"] is attn.q_norm.weight
|
||||
assert passed["main_k_norm_weight"] is attn.k_norm.weight
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("default_vllm_config")
|
||||
def test_qsa_unsupported_config_keeps_the_unfused_chain(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
indexer = _make_indexer(use_fused=False)
|
||||
monkeypatch.setattr(
|
||||
indexer_qsa,
|
||||
"qsa_prepare",
|
||||
lambda *args, **kwargs: pytest.fail("unfused path ran the fused kernel"),
|
||||
)
|
||||
updates = []
|
||||
monkeypatch.setattr(
|
||||
QSAIndexer,
|
||||
"_update_and_compress",
|
||||
lambda *args, **kwargs: updates.append(args),
|
||||
)
|
||||
rows = torch.tensor([[3, 1, -1], [5, 2, 0]], dtype=torch.int32)
|
||||
|
||||
actual, main_outputs = QSAIndexer.forward(
|
||||
indexer,
|
||||
torch.zeros(2, 8),
|
||||
torch.tensor([7, 8]),
|
||||
rows,
|
||||
attn=_make_attn(use_fused=False),
|
||||
)
|
||||
|
||||
assert actual is rows
|
||||
assert main_outputs is None
|
||||
assert len(updates) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("overrides", "expected"),
|
||||
[
|
||||
pytest.param({}, True, id="qwen3_8_flash_next"),
|
||||
pytest.param({"is_neox_style": False}, False, id="not-neox"),
|
||||
pytest.param({"rotary_dim": 128}, False, id="rotary-dim"),
|
||||
pytest.param({"mrope_interleaved": False}, False, id="mrope-not-interleaved"),
|
||||
pytest.param({"mrope_section": (11, 11, 10, 0)}, False, id="mrope-section-len"),
|
||||
],
|
||||
)
|
||||
def test_fused_pre_indexer_gate_is_config_shaped(overrides, expected) -> None:
|
||||
# Qwen3.8-Flash-Next's indexer geometry, which both vendors satisfy.
|
||||
rotary = SimpleNamespace(
|
||||
rotary_dim=64,
|
||||
is_neox_style=True,
|
||||
mrope_section=(11, 11, 10),
|
||||
mrope_interleaved=True,
|
||||
)
|
||||
for name, value in overrides.items():
|
||||
setattr(rotary, name, value)
|
||||
|
||||
assert (
|
||||
supports_fused_pre_indexer(
|
||||
rotary, head_dim=128, num_kv_heads=1, compress_ratio=4
|
||||
)
|
||||
is expected
|
||||
)
|
||||
|
||||
|
||||
def test_qsa_selection_uses_portable_topk_on_rocm(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
rows = 2
|
||||
token_topk = 8
|
||||
compress_ratio = 4
|
||||
block_topk = token_topk // compress_ratio
|
||||
blocks = torch.empty((rows, block_topk), dtype=torch.int32)
|
||||
visible_blocks = torch.tensor([4, 6], dtype=torch.int32)
|
||||
logits = torch.empty((rows, 8), dtype=torch.float32)
|
||||
selection_output = torch.empty(
|
||||
(rows, token_topk + compress_ratio - 1), dtype=torch.int32
|
||||
)
|
||||
topk_call: dict[str, Any] = {}
|
||||
|
||||
monkeypatch.setattr(
|
||||
qsa_ops,
|
||||
"qsa_mqa_paged",
|
||||
lambda *args, **kwargs: (logits, visible_blocks),
|
||||
)
|
||||
monkeypatch.setattr(qsa_ops.current_platform, "is_cuda", lambda: False)
|
||||
|
||||
def top_k_per_row_decode(
|
||||
topk_logits,
|
||||
next_n,
|
||||
seq_lens,
|
||||
raw_topk_indices,
|
||||
num_rows,
|
||||
stride0,
|
||||
stride1,
|
||||
topk_tokens,
|
||||
) -> None:
|
||||
topk_call.update(
|
||||
logits=topk_logits,
|
||||
next_n=next_n,
|
||||
seq_lens=seq_lens,
|
||||
raw_topk_indices=raw_topk_indices,
|
||||
num_rows=num_rows,
|
||||
strides=(stride0, stride1),
|
||||
topk_tokens=topk_tokens,
|
||||
)
|
||||
raw_topk_indices.zero_()
|
||||
|
||||
def expand_qsa_block_indices(*args) -> None:
|
||||
args[-1].fill_(-1)
|
||||
|
||||
monkeypatch.setattr(qsa_ops.ops, "top_k_per_row_decode", top_k_per_row_decode)
|
||||
monkeypatch.setattr(
|
||||
qsa_ops,
|
||||
"expand_qsa_block_indices_cuda",
|
||||
expand_qsa_block_indices,
|
||||
)
|
||||
|
||||
output = qsa_ops.qsa_select_paged_tokens(
|
||||
torch.empty((rows, 1, 1)),
|
||||
torch.empty((1, 4, 1, 1)),
|
||||
torch.empty((1, 2), dtype=torch.int32),
|
||||
torch.zeros(rows, dtype=torch.int32),
|
||||
torch.arange(rows, dtype=torch.int32),
|
||||
torch.tensor([8], dtype=torch.int32),
|
||||
token_topk,
|
||||
compress_ratio,
|
||||
selection_output,
|
||||
)
|
||||
|
||||
assert output is selection_output
|
||||
assert torch.all(output == -1)
|
||||
assert topk_call["logits"] is logits
|
||||
assert topk_call["next_n"] == 1
|
||||
assert topk_call["seq_lens"] is visible_blocks
|
||||
assert topk_call["raw_topk_indices"].shape == blocks.shape
|
||||
assert topk_call["num_rows"] == rows
|
||||
assert topk_call["strides"] == (logits.stride(0), logits.stride(1))
|
||||
assert topk_call["topk_tokens"] == block_topk
|
||||
|
||||
|
||||
@requires_qsa_kernels
|
||||
@pytest.mark.parametrize(
|
||||
("num_rows", "num_query_heads", "num_kv_heads", "page_size"),
|
||||
[
|
||||
pytest.param(1, 24, 2, 1792, id="tp1_split64"),
|
||||
pytest.param(16, 12, 1, 1792, id="tp2_split32"),
|
||||
pytest.param(32, 6, 1, 1024, id="tp4_split8"),
|
||||
pytest.param(257, 6, 1, 1024, id="tp4_split4"),
|
||||
pytest.param(513, 6, 1, 1024, id="tp4_split1"),
|
||||
],
|
||||
)
|
||||
def test_qsa_sparse_paged_attention_matches_reference(
|
||||
num_rows: int,
|
||||
num_query_heads: int,
|
||||
num_kv_heads: int,
|
||||
page_size: int,
|
||||
) -> None:
|
||||
torch.manual_seed(2)
|
||||
head_dim = 256
|
||||
num_requests = 2
|
||||
num_selected_pages = 64
|
||||
num_pages_per_request = num_selected_pages + 1
|
||||
num_cache_blocks = num_requests * num_pages_per_request
|
||||
indexer_budget = 2048
|
||||
indexer_compress_ratio = 4
|
||||
selection_width = indexer_budget + indexer_compress_ratio - 1
|
||||
q = torch.randn(
|
||||
num_rows, num_query_heads, head_dim, device="cuda", dtype=torch.bfloat16
|
||||
)
|
||||
kv_cache = torch.randn(
|
||||
num_cache_blocks,
|
||||
page_size,
|
||||
num_kv_heads,
|
||||
2 * head_dim,
|
||||
device="cuda",
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
k_cache, v_cache = kv_cache.split(head_dim, dim=-1)
|
||||
block_table = (
|
||||
torch.randperm(num_cache_blocks, device="cuda")
|
||||
.reshape(num_requests, num_pages_per_request)
|
||||
.to(torch.int32)
|
||||
)
|
||||
rows_per_request = math.ceil(num_rows / num_requests)
|
||||
row_indices = torch.arange(num_rows, device="cuda", dtype=torch.int32)
|
||||
token_to_req = row_indices // rows_per_request
|
||||
request_row_counts = torch.tensor(
|
||||
[rows_per_request, num_rows - rows_per_request],
|
||||
device="cuda",
|
||||
dtype=torch.int32,
|
||||
)
|
||||
|
||||
context_length = num_pages_per_request * page_size - 1
|
||||
block_topk = indexer_budget // indexer_compress_ratio
|
||||
compressed_blocks_per_page = page_size // indexer_compress_ratio
|
||||
selection = torch.arange(block_topk, device="cuda")
|
||||
selected_pages = selection % num_selected_pages
|
||||
selected_offsets = selection // num_selected_pages
|
||||
row_shifts = 2 * row_indices.unsqueeze(1)
|
||||
selected_offsets = (selected_offsets + row_shifts) % compressed_blocks_per_page
|
||||
block_indices = (selected_pages * compressed_blocks_per_page + selected_offsets).to(
|
||||
torch.int32
|
||||
)
|
||||
rows_within_request = row_indices % rows_per_request
|
||||
query_positions = (
|
||||
context_length - request_row_counts[token_to_req.long()] + rows_within_request
|
||||
).to(torch.int64)
|
||||
sequence_lengths = torch.full(
|
||||
(num_requests,), context_length, device="cuda", dtype=torch.int32
|
||||
)
|
||||
logical_indices = qsa_ops.expand_qsa_block_indices_cuda(
|
||||
block_indices,
|
||||
query_positions,
|
||||
sequence_lengths,
|
||||
token_to_req,
|
||||
indexer_compress_ratio,
|
||||
indexer_budget,
|
||||
)
|
||||
assert logical_indices.shape == (num_rows, selection_width)
|
||||
|
||||
actual = qsa_ops.qsa_sparse_paged_attention(
|
||||
q,
|
||||
k_cache,
|
||||
v_cache,
|
||||
logical_indices,
|
||||
block_table,
|
||||
token_to_req,
|
||||
)
|
||||
expected = _qsa_sparse_paged_attention_reference(
|
||||
q,
|
||||
k_cache,
|
||||
v_cache,
|
||||
logical_indices,
|
||||
block_table,
|
||||
token_to_req,
|
||||
q.shape[-1] ** -0.5,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(actual, expected, rtol=2e-2, atol=2e-2)
|
||||
@@ -1,418 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Correctness tests for the AMD fused QSA prepare kernel."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.models.qwen4_exp.amd.indexer_qsa import apply_qsa_rope
|
||||
from vllm.models.qwen4_exp.amd.ops.qsa import (
|
||||
qsa_compress_groups_with_ratio,
|
||||
qsa_store_cache_rows,
|
||||
)
|
||||
from vllm.models.qwen4_exp.amd.ops.qsa_prepare import qsa_prepare
|
||||
from vllm.models.qwen4_exp.common.qsa_cache import (
|
||||
canonical_qsa_rope_positions,
|
||||
circular_qsa_slot_mapping,
|
||||
compressed_qsa_slot_mapping,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
|
||||
requires_qsa_kernels = pytest.mark.skipif(
|
||||
not current_platform.is_rocm() or not HAS_TRITON,
|
||||
reason="the AMD QSA kernels require ROCm and Triton",
|
||||
)
|
||||
|
||||
|
||||
def _reference_gemma_rmsnorm(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
"""The unfused Gemma RMSNorm the AMD reference path actually runs."""
|
||||
norm = GemmaRMSNorm(weight.shape[-1], eps=eps).to(
|
||||
device=weight.device, dtype=weight.dtype
|
||||
)
|
||||
with torch.no_grad():
|
||||
norm.weight.copy_(weight)
|
||||
return norm.forward_native(x)
|
||||
|
||||
|
||||
HQ, D = 4, 128
|
||||
CR = 4
|
||||
MROPE_SECTION = (11, 11, 10)
|
||||
EPS = 1e-6
|
||||
BLOCK_SIZE = 16
|
||||
COMP_PAGE = BLOCK_SIZE // CR
|
||||
ROPE_POS_OFFSET = D
|
||||
RTOL = 1.6e-2
|
||||
ATOL = 1e-2
|
||||
MIXED_BATCH = ([260, 259, 138], [1, 1, 37], [8, 8, 8])
|
||||
MAIN_HQ, MAIN_HK, MAIN_D, MAIN_PAGE = 6, 2, 256, 16
|
||||
|
||||
|
||||
def _make_block_table(block_counts):
|
||||
# Block 0 is the null block, which no request owns.
|
||||
num_blocks = sum(block_counts) + 1
|
||||
table = torch.full((len(block_counts), max(block_counts)), -1, dtype=torch.int32)
|
||||
physical_blocks = torch.randperm(sum(block_counts)) + 1
|
||||
offset = 0
|
||||
for request, count in enumerate(block_counts):
|
||||
table[request, :count] = physical_blocks[offset : offset + count]
|
||||
offset += count
|
||||
return table, num_blocks
|
||||
|
||||
|
||||
def assert_fp8_within_one_ulp(actual: torch.Tensor, expected: torch.Tensor) -> None:
|
||||
# e4m3 is sign-magnitude, so within a sign the uint8 code order matches the
|
||||
# value order and one ulp is one code step. The two paths' intermediates
|
||||
# differ in the pooling accumulation order, which at denormal magnitudes
|
||||
# (absolute grid step 2^-9) shows up as up to 2 code steps.
|
||||
code_diff = (
|
||||
actual.view(torch.uint8).int() - expected.view(torch.uint8).int()
|
||||
).abs()
|
||||
abs_diff = (actual.float() - expected.float()).abs()
|
||||
assert bool(((code_diff <= 1) | (abs_diff <= 2**-8)).all())
|
||||
|
||||
|
||||
def _make_main_inputs(num_tokens: int) -> dict:
|
||||
"""Random main-attention arguments with a paged BF16 cache in vLLM's layout."""
|
||||
num_blocks = num_tokens // MAIN_PAGE + 2
|
||||
cache = torch.zeros(
|
||||
num_blocks,
|
||||
MAIN_HK,
|
||||
MAIN_PAGE,
|
||||
2 * MAIN_D,
|
||||
dtype=torch.bfloat16,
|
||||
device="cuda",
|
||||
).transpose(1, 2)
|
||||
slots = torch.randperm(num_blocks * MAIN_PAGE, device="cuda")[:num_tokens]
|
||||
slots[-1] = -1
|
||||
norm_weights = torch.randn(2, MAIN_D, dtype=torch.bfloat16, device="cuda") * 0.2
|
||||
return dict(
|
||||
main_qkv=torch.randn(
|
||||
num_tokens,
|
||||
2 * (MAIN_HQ + MAIN_HK) * MAIN_D,
|
||||
dtype=torch.bfloat16,
|
||||
device="cuda",
|
||||
),
|
||||
main_q_norm_weight=norm_weights[0],
|
||||
main_k_norm_weight=norm_weights[1],
|
||||
main_eps=EPS,
|
||||
main_kv_cache=cache,
|
||||
main_slot_mapping=slots,
|
||||
main_k_scale=1.0,
|
||||
main_v_scale=1.0,
|
||||
# The AMD op hands the gate back through a buffer it does not own.
|
||||
main_gate_out=torch.empty(
|
||||
num_tokens, MAIN_HQ, MAIN_D, dtype=torch.bfloat16, device="cuda"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _check_main_outputs(main: dict, q_out, gate_out, rope, positions) -> None:
|
||||
"""Compare with the AMD layer's unfused split, QK-norm, RoPE and cache write."""
|
||||
from vllm._custom_ops import reshape_and_cache_flash
|
||||
|
||||
num_tokens = main["main_qkv"].shape[0]
|
||||
q_gate, k, v = main["main_qkv"].split(
|
||||
[2 * MAIN_HQ * MAIN_D, MAIN_HK * MAIN_D, MAIN_HK * MAIN_D], dim=-1
|
||||
)
|
||||
q, gate = torch.chunk(q_gate.view(num_tokens, MAIN_HQ, -1), 2, dim=-1)
|
||||
q = _reference_gemma_rmsnorm(
|
||||
q.reshape(-1, MAIN_D), main["main_q_norm_weight"], EPS
|
||||
).view(num_tokens, -1)
|
||||
k = _reference_gemma_rmsnorm(
|
||||
k.reshape(-1, MAIN_D), main["main_k_norm_weight"], EPS
|
||||
).view(num_tokens, -1)
|
||||
q, k = rope(positions, q, k)
|
||||
kv_cache = main["main_kv_cache"]
|
||||
cache = torch.zeros_like(kv_cache)
|
||||
key_cache, value_cache = cache.split(MAIN_D, dim=-1)
|
||||
scale = torch.tensor(1.0, device="cuda")
|
||||
reshape_and_cache_flash(
|
||||
k.view(-1, MAIN_HK, MAIN_D),
|
||||
v.view(-1, MAIN_HK, MAIN_D),
|
||||
key_cache,
|
||||
value_cache,
|
||||
main["main_slot_mapping"],
|
||||
"auto",
|
||||
scale,
|
||||
scale,
|
||||
)
|
||||
torch.testing.assert_close(q_out.flatten(1), q, rtol=RTOL, atol=ATOL)
|
||||
assert torch.equal(gate_out, gate)
|
||||
torch.testing.assert_close(kv_cache, cache, rtol=RTOL, atol=ATOL)
|
||||
|
||||
|
||||
@requires_qsa_kernels
|
||||
@pytest.mark.usefixtures("default_vllm_config")
|
||||
@pytest.mark.parametrize("indexer_dtype", [torch.bfloat16, torch.float8_e4m3fn])
|
||||
@pytest.mark.parametrize(
|
||||
"mrope,is_2d_positions,cache_rope_positions,state_size,seq_lens,query_lens,history_lens",
|
||||
[
|
||||
pytest.param(True, True, True, 4, *MIXED_BATCH, id="mrope"),
|
||||
pytest.param(False, False, False, 4, *MIXED_BATCH, id="text"),
|
||||
pytest.param(True, False, True, 8, *MIXED_BATCH, id="mrope-model-1d"),
|
||||
pytest.param(True, True, False, 4, *MIXED_BATCH, id="mrope-no-position-cache"),
|
||||
pytest.param(
|
||||
True,
|
||||
False,
|
||||
False,
|
||||
8,
|
||||
*MIXED_BATCH,
|
||||
id="mrope-model-1d-no-position-cache",
|
||||
),
|
||||
pytest.param(
|
||||
False, False, True, 4, *MIXED_BATCH, id="text-with-position-cache"
|
||||
),
|
||||
pytest.param(True, True, True, 4, [37], [37], [0], id="fresh"),
|
||||
pytest.param(True, True, True, 4, [4097], [4097], [0], id="tiled"),
|
||||
],
|
||||
)
|
||||
def test_qsa_fused_prepare_matches_unfused(
|
||||
indexer_dtype,
|
||||
mrope,
|
||||
is_2d_positions,
|
||||
cache_rope_positions,
|
||||
state_size,
|
||||
seq_lens,
|
||||
query_lens,
|
||||
history_lens,
|
||||
) -> None:
|
||||
from vllm.model_executor.layers.rotary_embedding import get_rope
|
||||
|
||||
if indexer_dtype == torch.float8_e4m3fn:
|
||||
pytest.skip("the AMD QSA indexer cache is bf16-only")
|
||||
|
||||
# The FP8 comparison below is a one-ulp bound on data this test generates,
|
||||
# so an unseeded run decides for itself whether it reproduces a rounding
|
||||
# difference. Seed it, or the kernel's bit-exactness is only sampled.
|
||||
torch.manual_seed(0)
|
||||
|
||||
device = "cuda"
|
||||
rope_params = {
|
||||
"partial_rotary_factor": 0.25,
|
||||
"rope_theta": 10000000,
|
||||
"rope_type": "default",
|
||||
}
|
||||
if mrope:
|
||||
rope_params["mrope_interleaved"] = True
|
||||
rope_params["mrope_section"] = list(MROPE_SECTION)
|
||||
with torch.device(device):
|
||||
rope = get_rope(
|
||||
head_size=256,
|
||||
max_position=32768,
|
||||
rope_parameters=rope_params,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
token_to_req = torch.cat(
|
||||
[
|
||||
torch.full((length,), request, dtype=torch.int32)
|
||||
for request, length in enumerate(query_lens)
|
||||
]
|
||||
).to(device)
|
||||
logical_positions = torch.cat(
|
||||
[
|
||||
torch.arange(seq_len - query_len, seq_len, dtype=torch.int64)
|
||||
for seq_len, query_len in zip(seq_lens, query_lens)
|
||||
]
|
||||
).to(device)
|
||||
num_tokens = logical_positions.numel()
|
||||
query_start_loc = torch.tensor(
|
||||
[0, *torch.tensor(query_lens).cumsum(0).tolist()], dtype=torch.int32
|
||||
).to(device)
|
||||
positions = (
|
||||
torch.stack(
|
||||
[
|
||||
logical_positions,
|
||||
logical_positions // 7 + 3,
|
||||
logical_positions // 13 + 11,
|
||||
]
|
||||
)
|
||||
if is_2d_positions
|
||||
else logical_positions
|
||||
)
|
||||
position_rows = (
|
||||
canonical_qsa_rope_positions(positions)
|
||||
if cache_rope_positions
|
||||
else logical_positions.view(-1, 1, 1).expand(-1, 1, 3)
|
||||
)
|
||||
|
||||
compressed_block_counts = [
|
||||
(seq_len // CR + COMP_PAGE - 1) // COMP_PAGE for seq_len in seq_lens
|
||||
]
|
||||
raw_block_table, num_raw_blocks = _make_block_table([1] * len(seq_lens))
|
||||
compressed_block_table, num_compressed_blocks = _make_block_table(
|
||||
compressed_block_counts
|
||||
)
|
||||
raw_block_table = raw_block_table.to(device)
|
||||
raw_slots = circular_qsa_slot_mapping(
|
||||
raw_block_table,
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
state_size,
|
||||
query_start_loc,
|
||||
)
|
||||
compressed_slots = compressed_qsa_slot_mapping(
|
||||
compressed_block_table.to(device),
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
COMP_PAGE,
|
||||
CR,
|
||||
)
|
||||
group_counts = torch.tensor(
|
||||
[
|
||||
seq_len // CR - (seq_len - query_len) // CR
|
||||
for seq_len, query_len in zip(seq_lens, query_lens)
|
||||
],
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
)
|
||||
k_work_counts = torch.maximum(group_counts, torch.ones_like(group_counts))
|
||||
k_start_loc = torch.cat([k_work_counts.new_zeros(1), k_work_counts.cumsum(0)])
|
||||
work_requests = torch.repeat_interleave(
|
||||
torch.arange(len(query_lens), dtype=torch.int32, device=device),
|
||||
k_work_counts,
|
||||
)
|
||||
local_work = torch.arange(
|
||||
int(k_start_loc[-1]), dtype=torch.int32, device=device
|
||||
) - torch.repeat_interleave(k_start_loc[:-1], k_work_counts)
|
||||
max_k_work = (num_tokens + (CR - 1) * len(query_lens)) // CR
|
||||
k_work_metadata = torch.full((max_k_work, 2), -1, dtype=torch.int32, device=device)
|
||||
k_work_metadata[: work_requests.numel()] = torch.stack(
|
||||
(work_requests, local_work), dim=1
|
||||
)
|
||||
|
||||
raw_width = D + 12 if cache_rope_positions else D
|
||||
# Match vLLM's padded-page cache layout: rows are contiguous, while physical
|
||||
# blocks have a larger stride than their logical contents.
|
||||
raw_page_elements = state_size * raw_width
|
||||
fused_raw_storage = torch.zeros(
|
||||
num_raw_blocks,
|
||||
raw_page_elements + 16,
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
fused_raw = torch.as_strided(
|
||||
fused_raw_storage,
|
||||
(num_raw_blocks, state_size, 1, raw_width),
|
||||
(raw_page_elements + 16, raw_width, raw_width, 1),
|
||||
)
|
||||
for request, history_len in enumerate(history_lens):
|
||||
history_end = seq_lens[request] - query_lens[request]
|
||||
for position in range(history_end - history_len, history_end):
|
||||
block = int(raw_block_table[request, 0])
|
||||
row = fused_raw[block, position % state_size, 0]
|
||||
row[:D] = torch.randn(D, dtype=torch.bfloat16, device=device)
|
||||
if cache_rope_positions:
|
||||
row[ROPE_POS_OFFSET:].view(torch.int64).copy_(
|
||||
torch.tensor(
|
||||
[position, position // 7 + 3, position // 13 + 11],
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
)
|
||||
unfused_raw = fused_raw.clone()
|
||||
compressed_page_elements = COMP_PAGE * D
|
||||
fused_compressed_storage = torch.zeros(
|
||||
num_compressed_blocks,
|
||||
compressed_page_elements + 16,
|
||||
dtype=indexer_dtype,
|
||||
device=device,
|
||||
)
|
||||
fused_compressed = torch.as_strided(
|
||||
fused_compressed_storage,
|
||||
(num_compressed_blocks, COMP_PAGE, 1, D),
|
||||
(compressed_page_elements + 16, D, D, 1),
|
||||
)
|
||||
unfused_compressed = fused_compressed.clone()
|
||||
|
||||
projected_qk = torch.randn(
|
||||
num_tokens, (HQ + 1) * D, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
q_weight = torch.randn(D, dtype=torch.bfloat16, device=device) * 0.2
|
||||
k_weight = torch.randn(D, dtype=torch.bfloat16, device=device) * 0.2
|
||||
|
||||
fused_query = torch.empty(num_tokens, HQ, D, dtype=indexer_dtype, device=device)
|
||||
main = _make_main_inputs(num_tokens)
|
||||
main_q_out, main_gate_out = qsa_prepare(
|
||||
projected_qk[:, : HQ * D],
|
||||
projected_qk[:, HQ * D :],
|
||||
positions,
|
||||
rope.cos_sin_cache,
|
||||
q_weight,
|
||||
k_weight,
|
||||
EPS,
|
||||
fused_query,
|
||||
fused_raw,
|
||||
raw_slots,
|
||||
raw_block_table,
|
||||
query_start_loc,
|
||||
logical_positions,
|
||||
fused_compressed,
|
||||
compressed_slots,
|
||||
k_work_metadata,
|
||||
compress_ratio=CR,
|
||||
mrope_section=MROPE_SECTION if mrope else None,
|
||||
rope_pos_offset=ROPE_POS_OFFSET if cache_rope_positions else None,
|
||||
**main,
|
||||
)
|
||||
assert main_gate_out is main["main_gate_out"]
|
||||
_check_main_outputs(main, main_q_out, main_gate_out, rope, positions)
|
||||
|
||||
unfused_query = projected_qk[:, : HQ * D].reshape(num_tokens, HQ, D)
|
||||
unfused_query = _reference_gemma_rmsnorm(
|
||||
unfused_query.reshape(-1, D), q_weight, EPS
|
||||
).reshape_as(unfused_query)
|
||||
unfused_query = apply_qsa_rope(rope, positions, unfused_query)
|
||||
|
||||
raw_keys = unfused_raw[..., :D]
|
||||
rope_positions = (
|
||||
unfused_raw[..., ROPE_POS_OFFSET:].view(torch.int64)
|
||||
if cache_rope_positions
|
||||
else None
|
||||
)
|
||||
pooled, first_positions = qsa_compress_groups_with_ratio(
|
||||
projected_qk[:, HQ * D :].reshape(-1, 1, D),
|
||||
position_rows,
|
||||
raw_keys,
|
||||
raw_block_table,
|
||||
token_to_req,
|
||||
query_start_loc,
|
||||
logical_positions,
|
||||
compressed_slots,
|
||||
CR,
|
||||
rope_positions,
|
||||
)
|
||||
compressed_rows = _reference_gemma_rmsnorm(
|
||||
pooled.reshape(-1, D), k_weight, EPS
|
||||
).reshape(-1, 1, D)
|
||||
group_positions = (
|
||||
first_positions.transpose(0, 1) if mrope else first_positions[:, 0]
|
||||
)
|
||||
compressed_rows = apply_qsa_rope(rope, group_positions, compressed_rows)
|
||||
qsa_store_cache_rows(unfused_compressed, compressed_slots, compressed_rows)
|
||||
qsa_store_cache_rows(raw_keys, raw_slots, projected_qk[:, HQ * D :])
|
||||
if rope_positions is not None:
|
||||
qsa_store_cache_rows(rope_positions, raw_slots, position_rows)
|
||||
|
||||
if indexer_dtype == torch.float8_e4m3fn:
|
||||
# Both paths round the same ~bf16 intermediates to e4m3. Bitwise
|
||||
# equality (the dsv4 indexer test's bar) does not hold here: the 1D
|
||||
# reference rope (forward_cuda) differs from _norm_rope by up to 1
|
||||
# bf16 ulp, and even the MRoPE pair flips a code occasionally.
|
||||
unfused_query = unfused_query.to(indexer_dtype)
|
||||
assert_fp8_within_one_ulp(fused_query, unfused_query)
|
||||
else:
|
||||
torch.testing.assert_close(fused_query, unfused_query, rtol=RTOL, atol=ATOL)
|
||||
assert torch.equal(fused_raw.view(torch.int16), unfused_raw.view(torch.int16))
|
||||
if indexer_dtype == torch.float8_e4m3fn:
|
||||
assert_fp8_within_one_ulp(fused_compressed, unfused_compressed)
|
||||
else:
|
||||
torch.testing.assert_close(
|
||||
fused_compressed, unfused_compressed, rtol=RTOL, atol=ATOL
|
||||
)
|
||||
@@ -1,312 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Multi-GPU equivalence tests for Qwen4Exp HC and MoE sequence parallelism."""
|
||||
|
||||
from dataclasses import MISSING, fields
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.multiprocessing as mp
|
||||
from torch import nn
|
||||
from transformers import Qwen4ExpTextConfig
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda_alike():
|
||||
pytest.skip("Qwen4Exp SP requires CUDA or ROCm", allow_module_level=True)
|
||||
|
||||
from tests.utils import multi_gpu_test
|
||||
from vllm.config import (
|
||||
EngramConfig,
|
||||
ParallelConfig,
|
||||
VllmConfig,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.distributed import (
|
||||
cleanup_dist_env_and_memory,
|
||||
init_distributed_environment,
|
||||
initialize_model_parallel,
|
||||
tensor_model_parallel_all_reduce,
|
||||
)
|
||||
from vllm.forward_context import set_forward_context
|
||||
from vllm.model_executor.layers.linear import RowParallelLinear
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import is_conv_state_dim_first
|
||||
from vllm.models.common.ops.sequence_parallel import (
|
||||
sp_all_gather,
|
||||
sp_padding_mask,
|
||||
sp_shard,
|
||||
)
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
from vllm.v1.attention.backends.short_conv_attn import PleShortConvAttentionMetadata
|
||||
from vllm.v1.worker.workspace import init_workspace_manager, reset_workspace_manager
|
||||
|
||||
from .test_ple import _ConvBatchCase, _make_conv_metadata
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from vllm.models.qwen4_exp.amd import model as qwen4_model
|
||||
from vllm.models.qwen4_exp.amd.model import Qwen4ExpDecoderLayer
|
||||
else:
|
||||
from vllm.models.qwen4_exp.nvidia import model as qwen4_model
|
||||
from vllm.models.qwen4_exp.nvidia.model import Qwen4ExpDecoderLayer
|
||||
|
||||
|
||||
class _TPAttentionProjection(nn.Module):
|
||||
"""Keep real TP communication without setting up an attention KV cache."""
|
||||
|
||||
def __init__(self, config, *, reduce_results: bool, **kwargs) -> None:
|
||||
super().__init__()
|
||||
self.proj = RowParallelLinear(
|
||||
config.hidden_size,
|
||||
config.hidden_size,
|
||||
bias=False,
|
||||
input_is_parallel=False,
|
||||
reduce_results=reduce_results,
|
||||
)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor):
|
||||
return self.proj(hidden_states)[0]
|
||||
|
||||
|
||||
def _make_config(rank: int, *, hc_sp: bool = False, moe_sp: bool = False) -> VllmConfig:
|
||||
"""Configure HC SP explicitly or MoE SP through TP=2, DP=2 and EP."""
|
||||
config = VllmConfig(
|
||||
parallel_config=ParallelConfig(
|
||||
tensor_parallel_size=2,
|
||||
data_parallel_size=2 if moe_sp else 1,
|
||||
data_parallel_rank=rank // 2,
|
||||
enable_expert_parallel=moe_sp,
|
||||
enable_hc_sp=hc_sp,
|
||||
all2all_backend="allgather_reducescatter",
|
||||
),
|
||||
)
|
||||
config.model_config = SimpleNamespace(
|
||||
architecture="Qwen4ExpForCausalLM",
|
||||
is_moe=True,
|
||||
sleep_mode_offload_cudagraph=False,
|
||||
hf_text_config=Qwen4ExpTextConfig(
|
||||
vocab_size=128,
|
||||
eos_token_id=0,
|
||||
hidden_size=128,
|
||||
hc_count=2,
|
||||
hc_lowrank=16,
|
||||
num_hidden_layers=1,
|
||||
layer_types=["linear_attention"],
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
moe_intermediate_size=256,
|
||||
shared_expert_intermediate_size=256,
|
||||
ple_layer_ids=[] if moe_sp else [1],
|
||||
ple_embed_dim=128,
|
||||
heads_per_ngram=2,
|
||||
ngram_vocab_size_base=32,
|
||||
make_ngram_vocab_size_divisible_by=64,
|
||||
),
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
config.engram_config = EngramConfig(cpu_offload=False)
|
||||
return config
|
||||
|
||||
|
||||
def _make_decoder(config: VllmConfig, rank: int) -> Qwen4ExpDecoderLayer:
|
||||
"""Use the production constructor and identical initial weights for both modes."""
|
||||
with (
|
||||
set_current_vllm_config(config),
|
||||
patch.object(qwen4_model, "QwenGatedDeltaNetAttention", _TPAttentionProjection),
|
||||
):
|
||||
layer = Qwen4ExpDecoderLayer(
|
||||
config, config.model_config.hf_text_config.layer_types[0], "model.layers.0"
|
||||
)
|
||||
torch.manual_seed(12)
|
||||
for param in layer.parameters():
|
||||
param.normal_(std=0.08)
|
||||
# Distinct rank contributions expose missing or duplicate reductions.
|
||||
layer.linear_attn.proj.weight.add_(rank * 0.01)
|
||||
experts = layer.mlp.experts.routed_experts
|
||||
if config.parallel_config.enable_expert_parallel:
|
||||
experts.w13_weight.add_(rank * 0.01)
|
||||
experts.quant_method.process_weights_after_loading(experts)
|
||||
return layer
|
||||
|
||||
|
||||
def _check_decoder_ple(rank: int) -> None:
|
||||
"""Compare HC SP with full tokens across a PLE prefill and cached decode."""
|
||||
configs = [_make_config(rank, hc_sp=enabled) for enabled in (False, True)]
|
||||
layers = [_make_decoder(config, rank) for config in configs]
|
||||
states = []
|
||||
for layer in layers:
|
||||
ple = layer.ple
|
||||
assert ple is not None
|
||||
state = torch.zeros(2, ple.hc_hidden_size, ple.conv_state_len)
|
||||
if not is_conv_state_dim_first():
|
||||
state = state.transpose(-1, -2).contiguous()
|
||||
ple.kv_cache = (state,)
|
||||
states.append(state)
|
||||
|
||||
# Three prefill tokens straddle the TP=2 boundary and require SP padding.
|
||||
for case in (
|
||||
_ConvBatchCase(prefill_query_lens=(3,)),
|
||||
_ConvBatchCase(num_decodes=1),
|
||||
):
|
||||
layout, num_tokens = _make_conv_metadata(case, torch.device("cuda", rank))
|
||||
metadata_args = {
|
||||
f.name: None
|
||||
for f in fields(PleShortConvAttentionMetadata)
|
||||
if f.default is MISSING and f.default_factory is MISSING
|
||||
}
|
||||
metadata = PleShortConvAttentionMetadata(**(metadata_args | vars(layout)))
|
||||
ids = torch.randint(0, 128, (num_tokens,))
|
||||
positions = torch.arange(num_tokens).expand(3, -1)
|
||||
qsl = torch.tensor([0, num_tokens], dtype=torch.int32)
|
||||
context = torch.zeros(1, layers[0].config.ngram_size - 1, dtype=torch.int64)
|
||||
hidden = torch.randn(num_tokens, 256)
|
||||
block = torch.randn(num_tokens, 128)
|
||||
injection = torch.randn(num_tokens, 2)
|
||||
outputs = []
|
||||
for config, layer in zip(configs, layers):
|
||||
assert layer.ple is not None
|
||||
inputs = (hidden, block, injection)
|
||||
if config.parallel_config.enable_hc_sp:
|
||||
inputs = tuple(sp_shard(x) for x in inputs)
|
||||
with (
|
||||
set_current_vllm_config(config),
|
||||
set_forward_context({layer.ple.prefix: metadata}, config),
|
||||
):
|
||||
if hasattr(layer.ple, "start_prefetch"):
|
||||
layer.ple.start_prefetch(ids, qsl, context)
|
||||
output = layer(
|
||||
*inputs,
|
||||
positions,
|
||||
input_ids=ids,
|
||||
query_start_loc=qsl,
|
||||
ngram_context=context,
|
||||
)
|
||||
if config.parallel_config.enable_hc_sp:
|
||||
# ROCm all-gather requires contiguous inputs.
|
||||
output = tuple(
|
||||
sp_all_gather(x.contiguous())[:num_tokens] for x in output
|
||||
)
|
||||
# A later MoE call may reuse workspace-backed output storage.
|
||||
outputs.append(tuple(x.clone() for x in output))
|
||||
torch.testing.assert_close(outputs[1], outputs[0], atol=0.002, rtol=0.02)
|
||||
torch.testing.assert_close(states[1], states[0], atol=0.002, rtol=0.02)
|
||||
|
||||
|
||||
def _check_moe_sp(rank: int, config: VllmConfig) -> None:
|
||||
"""Compare native SP with full-token GR and the MoE wrapper's public interface."""
|
||||
layer = _make_decoder(config, rank)
|
||||
dp_rank = config.parallel_config.data_parallel_rank
|
||||
counts = torch.tensor([3, 5], device="cpu")
|
||||
num_tokens = int(counts[dp_rank])
|
||||
torch.manual_seed(30 + dp_rank)
|
||||
hidden = torch.randn(num_tokens, 256)
|
||||
positions = torch.arange(num_tokens)
|
||||
# Include runner padding in addition to the padding introduced by SP.
|
||||
padding = sp_padding_mask(positions == num_tokens - 1, hidden)
|
||||
with (
|
||||
set_current_vllm_config(config),
|
||||
set_forward_context(
|
||||
None,
|
||||
config,
|
||||
num_tokens=num_tokens,
|
||||
num_tokens_across_dp=counts,
|
||||
is_padding=padding,
|
||||
),
|
||||
):
|
||||
# The reference keeps full GR rows. MoE handles its own chunk and gather.
|
||||
full_hidden, attn_input, injection = layer.attn_hyper_connection.mix(hidden)
|
||||
attn_output = tensor_model_parallel_all_reduce(layer.linear_attn(attn_input))
|
||||
full_hidden, moe_input, injection = layer.mlp_hyper_connection.combine_and_mix(
|
||||
full_hidden, attn_output, injection
|
||||
)
|
||||
expected = tuple(
|
||||
x.clone() for x in (full_hidden, layer.mlp(moe_input), injection)
|
||||
)
|
||||
output = layer(
|
||||
sp_shard(hidden),
|
||||
None,
|
||||
None,
|
||||
positions,
|
||||
input_ids=None,
|
||||
query_start_loc=None,
|
||||
ngram_context=None,
|
||||
)
|
||||
actual = tuple(sp_all_gather(x.contiguous())[:num_tokens] for x in output)
|
||||
torch.testing.assert_close(actual, expected, atol=0.002, rtol=0.02)
|
||||
|
||||
|
||||
def _check_compiled_sp_ops() -> None:
|
||||
"""Compiled SP collectives stay correct for token counts unseen at trace time."""
|
||||
from vllm.models.qwen4_exp.amd.ops.sequence_parallel import (
|
||||
sp_reduce_scatter,
|
||||
sp_shard,
|
||||
)
|
||||
|
||||
def collectives(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
gathered = sp_all_gather(sp_shard(x) * 2)[: x.shape[0]]
|
||||
reduced = sp_all_gather(sp_reduce_scatter(x))[: x.shape[0]]
|
||||
return gathered, reduced
|
||||
|
||||
# vLLM drops Dynamo guards, so one trace must serve every token count.
|
||||
compiled = torch.compile(
|
||||
collectives,
|
||||
fullgraph=True,
|
||||
options={"guard_filter_fn": torch.compiler.skip_all_guards_unsafe},
|
||||
)
|
||||
traced = torch.randn(8, 16)
|
||||
torch._dynamo.mark_dynamic(traced, 0)
|
||||
compiled(traced)
|
||||
for num_tokens in (7, 3, 1):
|
||||
torch.manual_seed(num_tokens)
|
||||
x = torch.randn(num_tokens, 16)
|
||||
torch.testing.assert_close(compiled(x), collectives(x), atol=0, rtol=0)
|
||||
|
||||
|
||||
def _run_sp(rank: int, port: int, moe_sp: bool, compiled_ops: bool = False) -> None:
|
||||
"""Initialize rank-local runtime state and run one equivalence check."""
|
||||
torch.accelerator.set_device_index(rank)
|
||||
torch.set_num_threads(1)
|
||||
config = _make_config(rank, moe_sp=moe_sp)
|
||||
init_distributed_environment(
|
||||
world_size=4 if moe_sp else 2,
|
||||
rank=rank,
|
||||
local_rank=rank,
|
||||
distributed_init_method=f"tcp://127.0.0.1:{port}",
|
||||
)
|
||||
try:
|
||||
# Spawned ranks bypass the GPU worker's workspace initialization.
|
||||
init_workspace_manager(torch.device(f"cuda:{rank}"))
|
||||
with set_current_vllm_config(config):
|
||||
initialize_model_parallel(tensor_model_parallel_size=2)
|
||||
with torch.device(f"cuda:{rank}"), torch.inference_mode():
|
||||
torch.set_default_dtype(torch.bfloat16)
|
||||
if moe_sp:
|
||||
_check_moe_sp(rank, config)
|
||||
elif compiled_ops:
|
||||
_check_compiled_sp_ops()
|
||||
else:
|
||||
_check_decoder_ple(rank)
|
||||
finally:
|
||||
reset_workspace_manager()
|
||||
cleanup_dist_env_and_memory()
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
def test_hc_sp_decoder_and_ple() -> None:
|
||||
"""HC SP preserves decoder output and PLE cache across a token-shard boundary."""
|
||||
mp.spawn(_run_sp, args=(get_open_port(), False), nprocs=2)
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=4)
|
||||
def test_moe_sp_equivalence(monkeypatch) -> None:
|
||||
"""Native MoE SP preserves outputs with unequal DP batches and padding."""
|
||||
monkeypatch.setenv("VLLM_MOE_SKIP_PADDING", "1")
|
||||
mp.spawn(_run_sp, args=(get_open_port(), True), nprocs=4)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm-only SP ops")
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
def test_compiled_sp_ops_handle_untraced_token_counts() -> None:
|
||||
"""Padding in compiled SP collectives must not specialize on the traced size."""
|
||||
mp.spawn(_run_sp, args=(get_open_port(), False, True), nprocs=2)
|
||||
Reference in New Issue
Block a user