test_silu_mul_quant_fusion.py 5.76 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
from typing import cast

5
6
7
8
import pytest
import torch

import vllm.envs as envs
9
from tests.kernels.quantization.nvfp4_utils import quant_nvfp4_tensor
10
11
12
13
14
15
16
from vllm._custom_ops import cutlass_scaled_fp4_mm, scaled_fp4_quant
# yapf conflicts with isort for this block
# yapf: disable
from vllm.compilation.activation_quant_fusion import (
    FUSED_OPS, SILU_MUL_OP, ActivationQuantFusionPass)
# yapf: enable
from vllm.compilation.fusion import QUANT_OPS
17
from vllm.compilation.noop_elimination import NoOpEliminationPass
18
from vllm.config import CompilationConfig, PassConfig, VllmConfig
19
from vllm.model_executor.layers.activation import SiluAndMul
20
from vllm.model_executor.layers.quantization.utils.quant_utils import (
21
    GroupShape, kFp8StaticTensorSym, kNvfp4Quant)
22
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
23
    Fp8LinearOp, cutlass_fp8_supported)
24
from vllm.platforms import current_platform
25

26
from ..utils import override_cutlass_fp8_supported
27
28
from .backend import TestBackend

29
30
FP8_DTYPE = current_platform.fp8_dtype()
FP4_DTYPE = torch.uint8
31
32


33
34
35
36
37
38
def is_nvfp4_supported():
    return current_platform.has_device_capability(100)


class TestSiluMulFp8QuantModel(torch.nn.Module):

39
    def __init__(self, hidden_size: int, cuda_force_torch: bool, **kwargs):
40
        super().__init__()
41
        self.silu_and_mul = SiluAndMul()
42
        self.wscale = torch.rand(1, dtype=torch.float32)
43
44
        self.scale = torch.rand(1, dtype=torch.float32)

45
        self.w = torch.rand(hidden_size, hidden_size).to(dtype=FP8_DTYPE).t()
46

47
48
49
50
51
        with override_cutlass_fp8_supported(not cuda_force_torch):
            self.fp8_linear = Fp8LinearOp(
                act_quant_static=True,
                act_quant_group_shape=GroupShape.PER_TENSOR,
            )
52

53
54
    def forward(self, x):
        y = self.silu_and_mul(x)
55
56
57
58
        x2 = self.fp8_linear.apply(y,
                                   self.w,
                                   self.wscale,
                                   input_scale=self.wscale)
59
60
        return x2

61
62
63
64
65
66
67
68
69
    def ops_in_model_before(self):
        return [SILU_MUL_OP, QUANT_OPS[kFp8StaticTensorSym]]

    def ops_in_model_after(self):
        return [FUSED_OPS[kFp8StaticTensorSym]]


class TestSiluMulNvfp4QuantModel(torch.nn.Module):

70
    def __init__(self, hidden_size: int, x: torch.Tensor, **kwargs):
71
72
        super().__init__()
        self.silu_and_mul = SiluAndMul()
73
74
75
76
77
78
79
80
81

        # create nvfp4 weight
        w = torch.rand((hidden_size, hidden_size))
        self.w, self.w_block_scale, self.w_global_scale = quant_nvfp4_tensor(w)

        # get global scale offline
        _, _, self.y_global_scale = quant_nvfp4_tensor(self.silu_and_mul(x))

        self.alpha = 1.0 / (self.w_global_scale * self.y_global_scale)
82

83
84
    def forward(self, x):
        y = self.silu_and_mul(x)
85
        y_quant, y_block_scale = scaled_fp4_quant(y, self.y_global_scale)
86
87
88
        out = cutlass_scaled_fp4_mm(a=y_quant,
                                    b=self.w,
                                    block_scale_a=y_block_scale,
89
90
                                    block_scale_b=self.w_block_scale,
                                    alpha=self.alpha,
91
92
93
94
95
96
97
98
99
100
                                    out_dtype=y.dtype)
        return out

    def ops_in_model_before(self):
        return [SILU_MUL_OP, QUANT_OPS[kNvfp4Quant]]

    def ops_in_model_after(self):
        return [FUSED_OPS[kNvfp4Quant]]


101
102
103
@pytest.mark.parametrize("num_tokens", [32, 64])
@pytest.mark.parametrize("hidden_size", [128, 256])
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
104
@pytest.mark.parametrize(
105
106
107
    "model_class",
    cast(list[type], [TestSiluMulFp8QuantModel, TestSiluMulNvfp4QuantModel]
         if is_nvfp4_supported() else [TestSiluMulFp8QuantModel]))
108
109
110
111
# cuda_force_torch used to test torch code path on platforms that
# cutlass_fp8_supported() == True.
@pytest.mark.parametrize("cuda_force_torch",
                         [True, False] if cutlass_fp8_supported() else [True])
112
113
@pytest.mark.skipif(envs.VLLM_TARGET_DEVICE not in ["cuda", "rocm"],
                    reason="Only test on CUDA and ROCm")
114
def test_fusion_silu_and_mul_quant(num_tokens, hidden_size, dtype, model_class,
115
116
                                   cuda_force_torch):
    if model_class == TestSiluMulNvfp4QuantModel and cuda_force_torch:
117
118
        pytest.skip("Duplicate tests for NVFP4")

119
    torch.set_default_device("cuda")
120
    torch.set_default_dtype(dtype)
121

122
123
    x = torch.rand(num_tokens, hidden_size * 2)

124
125
126
    # Reshape pass is needed for the fusion pass to work
    config = VllmConfig()
    config.compilation_config = CompilationConfig(
127
        pass_config=PassConfig(enable_fusion=True, enable_noop=True))
128
129
    fusion_pass = ActivationQuantFusionPass(config)

130
    backend = TestBackend(NoOpEliminationPass(config), fusion_pass)
131
    model = model_class(hidden_size=hidden_size,
132
133
                        cuda_force_torch=cuda_force_torch,
                        x=x)
134
135
136
137
138
139
140
141
142
143

    # First dimension dynamic
    torch._dynamo.mark_dynamic(x, 0)

    result = model(x)

    model2 = torch.compile(model, backend=backend)
    result2 = model2(x)

    # Check that it gives the same answer
144
145
146
147
148
    if model_class == TestSiluMulFp8QuantModel:
        atol, rtol = 1e-3, 1e-3
    elif model_class == TestSiluMulNvfp4QuantModel:
        atol, rtol = 1e-1, 1e-1

149
150
    torch.testing.assert_close(result[0].to(dtype=dtype),
                               result2[0].to(dtype=dtype),
151
152
                               atol=atol,
                               rtol=rtol)
153

154
155
    # In pre-nodes, quant op should be present and fused kernels should not
    backend.check_before_ops(model.ops_in_model_before())
156

157
158
    # In post-nodes, fused kernels should be present and quant op should not
    backend.check_after_ops(model.ops_in_model_after())