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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
275 changes: 253 additions & 22 deletions tests/kernels/quantization/test_rdna_hybrid_w4a16.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@
)
RDNAHybridW4A16LinearKernel = hybrid_module.RDNAHybridW4A16LinearKernel
pack_int4_exllama_shuffle = hybrid_module.pack_int4_exllama_shuffle
dequantize_w4a16 = hybrid_module.dequantize_w4a16
SUPPORTED_GROUP_SIZES = hybrid_module.SUPPORTED_GROUP_SIZES
MAX_SKINNY_BATCH_SIZE = hybrid_module.MAX_SKINNY_BATCH_SIZE
MIN_DENSE_M = hybrid_module.MIN_DENSE_M

# Per-channel (-1) is symmetric-only (see can_implement's zero_points guard),
# so it is only added to the group-size axis of tests that stay on the
Expand Down Expand Up @@ -79,33 +81,36 @@ def _build_packed_scale_zp(
return ((hi_u16 << 16) | scale_u16).view(torch.float32).contiguous()


def _rdna_hybrid_w4a16_reference(
x_mk: torch.Tensor,
def _dequant_reference(
w_int4_nk: torch.Tensor,
scales_nkg: torch.Tensor,
zp_nkg: torch.Tensor | None,
group_size: int,
bias: torch.Tensor | None,
) -> torch.Tensor:
"""Reference for the Hybrid W4A16 op.
"""fp32 [N, K] dequantized weight.

x_mk: [M, K] fp16/bf16
w_int4_nk: [N, K] int32 with raw uint4 values in [0, 15]
scales_nkg: [N, K//G] fp16/bf16
zp_nkg: [N, K//G] int32 raw zero points in [0, 15],
or None for symmetric (uint4b8, dequant subtracts 8)
group_size: -1 (per-channel, resolved to a single group of size K) or one
of SUPPORTED_GROUP_SIZES.
zp_nkg: [N, K//G] int32 raw zero points in [0, 15], or None for
symmetric (uint4b8, dequant subtracts 8)
"""
N, K = w_int4_nk.shape
G = K if group_size == -1 else group_size
assert K % G == 0
s_full = scales_nkg.repeat_interleave(G, dim=1).to(torch.float32) # [N, K]
if zp_nkg is None:
z_full = torch.full((N, K), 8.0, device=x_mk.device, dtype=torch.float32)
else:
z_full = zp_nkg.repeat_interleave(G, dim=1).to(torch.float32)
w_fp = (w_int4_nk.to(torch.float32) - z_full) * s_full # [N, K]
G = w_int4_nk.shape[1] if group_size == -1 else group_size
assert w_int4_nk.shape[1] % G == 0
s_full = scales_nkg.repeat_interleave(G, dim=1).to(torch.float32)
z_full = 8.0 if zp_nkg is None else zp_nkg.repeat_interleave(G, dim=1).float()
return (w_int4_nk.to(torch.float32) - z_full) * s_full


def _rdna_hybrid_w4a16_reference(
x_mk: torch.Tensor,
w_int4_nk: torch.Tensor,
scales_nkg: torch.Tensor,
zp_nkg: torch.Tensor | None,
group_size: int,
bias: torch.Tensor | None,
) -> torch.Tensor:
"""Reference for the Hybrid W4A16 op; x_mk is [M, K] fp16/bf16."""
w_fp = _dequant_reference(w_int4_nk, scales_nkg, zp_nkg, group_size)
out = x_mk.to(torch.float32) @ w_fp.t() # [M, N]
if bias is not None:
out = out + bias.to(torch.float32)
Expand All @@ -123,15 +128,19 @@ def _rdna_hybrid_w4a16_reference(
@pytest.mark.parametrize("has_zp", [False, True])
@pytest.mark.parametrize(
"M",
[1, MAX_SKINNY_BATCH_SIZE, MAX_SKINNY_BATCH_SIZE + 1, 64],
ids=["M=1_decode", "M=5_decode", "M=6_prefill", "M=64_prefill"],
[1, MAX_SKINNY_BATCH_SIZE, MAX_SKINNY_BATCH_SIZE + 1, 64, MIN_DENSE_M],
ids=["M=1_decode", "M=5_decode", "M=6_prefill", "M=64_prefill", "M=256_dense"],
)
def test_rdna_hybrid_w4a16_apply_matches_reference(dtype, group_size, has_zp, M):
@pytest.mark.parametrize("use_dequant", [False, True])
def test_rdna_hybrid_w4a16_apply_matches_reference(
dtype, group_size, has_zp, M, use_dequant
):
"""Smoke test the registered custom op for both decode and prefill batches.

Verifies the dispatch logic in `_rdna_hybrid_w4a16_apply_impl`:
- M <= MAX_SKINNY_BATCH_SIZE: HIP wvSplitK_int4_g
- M > MAX_SKINNY_BATCH_SIZE: Triton prefill kernel
- M >= MIN_DENSE_M with a dense copy: dense GEMM
- Other batches: Triton prefill kernel

group_size=-1 (per-channel) is symmetric-only (can_implement rejects it
with zero_points=True), so the has_zp=True combination is skipped for it
Expand Down Expand Up @@ -173,6 +182,12 @@ def test_rdna_hybrid_w4a16_apply_matches_reference(dtype, group_size, has_zp, M)
w_zp = None
packed_scale_zp = None

w_dequant = (
dequantize_w4a16(w_int4_nk, scales_nkg, zp_nkg, G, 0 if has_zp else 8, dtype)
if use_dequant
else None
)

from vllm.utils.platform_utils import num_compute_units

out = torch.ops.vllm.rdna_hybrid_w4a16_apply(
Expand All @@ -185,6 +200,7 @@ def test_rdna_hybrid_w4a16_apply_matches_reference(dtype, group_size, has_zp, M)
num_compute_units(),
group_size,
packed_scale_zp,
w_dequant,
)

ref = _rdna_hybrid_w4a16_reference(
Expand Down Expand Up @@ -458,6 +474,221 @@ def test_rdna_hybrid_w4a16_process_weights_asymmetric_repack(group_size, dist_in
torch.testing.assert_close(w_q_i32, expected_packed)


@pytest.mark.skipif(not on_gfx1x(), reason="Hybrid path is gfx11/gfx12 only")
@pytest.mark.parametrize(
"M,has_dense,expected_path",
[
(MAX_SKINNY_BATCH_SIZE, True, "hip"),
(MIN_DENSE_M - 1, True, "triton"),
(MIN_DENSE_M, True, "dense"),
(MIN_DENSE_M, False, "triton"),
],
ids=["decode", "below_dense_threshold", "at_dense_threshold", "off"],
)
def test_rdna_hybrid_w4a16_dense_dispatch(M, has_dense, expected_path, monkeypatch):
"""Memory-bound batches stay on int4 even when a dense copy exists."""
import vllm._custom_ops as ops

N, K, G = 16, 16384, 128

x_mk = torch.empty((M, K), dtype=torch.float16)
w_q = torch.empty((N, K // 2), dtype=torch.int8)
scales = torch.empty((N, K // G), dtype=torch.float16)
w_dequant = torch.empty((N, K), dtype=torch.float16) if has_dense else None
called = []

def fake(path):
def record(*args, **kwargs):
called.append(path)
return torch.empty((M, N), dtype=x_mk.dtype)

return record

monkeypatch.setattr(ops, "wvSplitK_int4_g", fake("hip"))
monkeypatch.setattr(hybrid_module, "triton_w4a16_skinny_fmt_gemm", fake("triton"))
monkeypatch.setattr(hybrid_module, "rocm_unquantized_gemm_impl", fake("dense"))
hybrid_module._rdna_hybrid_w4a16_apply_impl(
x_mk, w_q, scales, w_q.view(torch.int32), None, None, 40, G, None, w_dequant
)

assert called == [expected_path]


# ---------------------------------------------------------------------------
# process_weights_after_loading: rdna_hybrid_w4a16_prefill_dequant cache
# ---------------------------------------------------------------------------

_W_DEQUANT_ATTR = RDNAHybridW4A16LinearKernel.DEQUANT_WEIGHT_NAME


def _build_prefill_dequant_case(
K: int, N: int, G: int, has_zp: bool, dtype: torch.dtype = torch.float16
):
"""Return (layer, kernel, w_int4_nk, scales_nkg, zp_nkg) for a CT layer."""
from vllm.model_executor.kernels.linear.mixed_precision.MPLinearKernel import (
MPLinearLayerConfig,
)
from vllm.scalar_type import scalar_types

num_groups = K // (K if G == -1 else G)
w_int4_kn = torch.randint(0, 16, (K, N), device=device, dtype=torch.int32)
scales_nkg = 0.05 * torch.rand((N, num_groups), device=device, dtype=dtype)
if has_zp:
zeros_int4_gn = torch.randint(
0, 16, (num_groups, N), device=device, dtype=torch.int32
)
zeros_ckpt = _pack_int4_along_n_for_zp(zeros_int4_gn).t().contiguous()
zp_nkg = zeros_int4_gn.t().contiguous()
else:
zeros_ckpt = zp_nkg = None

layer = _build_dummy_layer(
_pack_int4_along_k_to_ckpt(w_int4_kn), scales_nkg, zeros_ckpt
)
config = MPLinearLayerConfig(
full_weight_shape=(K, N),
partition_weight_shape=(K, N),
weight_type=scalar_types.uint4 if has_zp else scalar_types.uint4b8,
act_type=dtype,
group_size=G,
zero_points=has_zp,
)
kernel = RDNAHybridW4A16LinearKernel(
config,
w_q_param_name="weight_packed",
w_s_param_name="weight_scale",
w_zp_param_name="weight_zero_point" if has_zp else None,
)
return layer, kernel, w_int4_kn.t().contiguous(), scales_nkg, zp_nkg


def _prefill_dequant_vllm_config(mode: str, gpu_memory_utilization: float):
from vllm.config import CacheConfig, KernelConfig, VllmConfig

return VllmConfig(
kernel_config=KernelConfig(rdna_hybrid_w4a16_prefill_dequant=mode),
cache_config=CacheConfig(gpu_memory_utilization=gpu_memory_utilization),
)


@pytest.mark.parametrize(
"value, expected",
[("Enable", "enable"), ("DISABLE", "disable"), (True, None), ("on", None)],
)
def test_rdna_hybrid_w4a16_prefill_dequant_mode_normalized(value, expected):
"""Mode strings are case-insensitive; booleans are not modes."""
from pydantic import ValidationError

from vllm.config import KernelConfig

if expected is None:
with pytest.raises(ValidationError):
KernelConfig(rdna_hybrid_w4a16_prefill_dequant=value)
else:
config = KernelConfig(rdna_hybrid_w4a16_prefill_dequant=value)
assert config.rdna_hybrid_w4a16_prefill_dequant == expected


@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("group_size,has_zp", [(128, False), (128, True), (-1, False)])
@pytest.mark.parametrize("mode", ["disable", "enable"])
def test_rdna_hybrid_w4a16_prefill_dequant_cached(
mode, group_size, has_zp, dtype, dist_init
):
"""Within budget, enabling caches the dense copy; disabled caches nothing."""
if not torch.cuda.is_available():
pytest.skip("CUDA/HIP device not available")

from vllm.config import set_current_vllm_config

set_random_seed(0)
K, N, G = 1024, 128, group_size
layer, kernel, w_int4_nk, scales_nkg, zp_nkg = _build_prefill_dequant_case(
K, N, G, has_zp, dtype
)

# Utilization 1.0 leaves all free memory in budget, so the tiny layer fits.
with set_current_vllm_config(_prefill_dequant_vllm_config(mode, 1.0)):
kernel.process_weights_after_loading(layer)

if mode == "disable":
assert not hasattr(layer, _W_DEQUANT_ATTR)
return

expected = _dequant_reference(w_int4_nk, scales_nkg, zp_nkg, G).to(dtype)
torch.testing.assert_close(
getattr(layer, _W_DEQUANT_ATTR), expected, rtol=0, atol=0
)
assert _W_DEQUANT_ATTR not in layer.state_dict()
assert _W_DEQUANT_ATTR not in dict(layer.named_parameters())
assert getattr(layer, _W_DEQUANT_ATTR).stride(0) > K


def test_rdna_hybrid_w4a16_prefill_dequant_budget_exhausted(dist_init, monkeypatch):
"""Over budget, enabling the cache raises instead of caching a subset."""
if not torch.cuda.is_available():
pytest.skip("CUDA/HIP device not available")

from types import SimpleNamespace

from vllm.config import set_current_vllm_config

# The real free memory is machine dependent; 40 GiB free with 50 GiB
# outside a 0.5 budget leaves nothing to spend.
monkeypatch.setattr(
hybrid_module,
"MemorySnapshot",
lambda device: SimpleNamespace(
free_memory=40 * 2**30, total_memory=100 * 2**30
),
)
set_random_seed(0)
layer, kernel, *_ = _build_prefill_dequant_case(256, 128, 128, has_zp=False)

with (
set_current_vllm_config(_prefill_dequant_vllm_config("enable", 0.5)),
pytest.raises(ValueError, match="gpu_memory_utilization"),
):
kernel.process_weights_after_loading(layer)


@pytest.mark.parametrize("min_kv_gib, fits", [(0, True), (8, False)])
def test_rdna_hybrid_w4a16_prefill_dequant_reserves_min_kv(
min_kv_gib, fits, dist_init, monkeypatch
):
"""The budget keeps room for one max_model_len request of KV cache."""
if not torch.cuda.is_available():
pytest.skip("CUDA/HIP device not available")

from types import SimpleNamespace

from vllm.config import set_current_vllm_config

# 60 GiB free with 50 GiB outside a 0.5 budget leaves 10 GiB, 6 GiB after
# the activation headroom: enough for the layer unless KV claims 8 GiB.
monkeypatch.setattr(
hybrid_module,
"MemorySnapshot",
lambda device: SimpleNamespace(
free_memory=60 * 2**30, total_memory=100 * 2**30
),
)
monkeypatch.setattr(
"vllm.v1.core.kv_cache_utils.max_memory_usage_bytes",
lambda vllm_config, specs: min_kv_gib * 2**30,
)
set_random_seed(0)
layer, kernel, *_ = _build_prefill_dequant_case(256, 128, 128, has_zp=False)

with set_current_vllm_config(_prefill_dequant_vllm_config("enable", 0.5)):
if fits:
kernel.process_weights_after_loading(layer)
assert hasattr(layer, _W_DEQUANT_ATTR)
else:
with pytest.raises(ValueError, match="gpu_memory_utilization"):
kernel.process_weights_after_loading(layer)


# ---------------------------------------------------------------------------
# can_implement enforces the supported-group-size policy
# ---------------------------------------------------------------------------
Expand Down
41 changes: 0 additions & 41 deletions tests/kernels/quantization/test_w4a16_prefill_dequant_config.py

This file was deleted.

Loading
Loading