test_fusion.py 7.15 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
6
import pytest
import torch

7
import vllm.plugins
8
9
10
from vllm.compilation.fusion import FUSED_OPS, FusedRMSQuantKey, RMSNormQuantFusionPass
from vllm.compilation.fx_utils import find_op_nodes
from vllm.compilation.matcher_utils import QUANT_OPS
11
from vllm.compilation.noop_elimination import NoOpEliminationPass
12
from vllm.compilation.post_cleanup import PostCleanupPass
13
14
15
16
17
18
19
from vllm.config import (
    CompilationConfig,
    CompilationMode,
    ModelConfig,
    PassConfig,
    VllmConfig,
)
20
from vllm.model_executor.layers.layernorm import RMSNorm
21
from vllm.model_executor.layers.quantization.utils.quant_utils import (
22
23
24
25
    GroupShape,
    QuantKey,
    ScaleDesc,
)
26
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
27
28
29
30
    Fp8LinearOp,
    cutlass_fp8_supported,
    maybe_create_device_identity,
)
31
from vllm.platforms import current_platform
32

33
from ..utils import override_cutlass_fp8_supported
34
35
from .backend import TestBackend

36
37
FP8_DTYPE = current_platform.fp8_dtype()

38
39
40
RMS_OP = torch.ops._C.rms_norm.default
RMS_ADD_OP = torch.ops._C.fused_add_rms_norm.default

41
42

class TestModel(torch.nn.Module):
43
44
45
46
47
48
49
50
51
    def __init__(
        self,
        hidden_size: int,
        eps: float,
        static: bool,
        cuda_force_torch: bool,
        *args,
        **kwargs,
    ):
52
        super().__init__(*args, **kwargs)
53
        self.cuda_force_torch = cuda_force_torch
54
55
        self.norm = [RMSNorm(hidden_size, eps) for _ in range(4)]
        self.wscale = [torch.rand(1, dtype=torch.float32) for _ in range(3)]
56
        group_shape = GroupShape.PER_TENSOR if static else GroupShape.PER_TOKEN
57
        quant_scale = ScaleDesc(torch.float32, static, group_shape)
58
        self.quant_key = QuantKey(dtype=FP8_DTYPE, scale=quant_scale, symmetric=True)
59
        if static:
60
            self.scale = [torch.rand(1, dtype=torch.float32) for _ in range(3)]
61
        else:
62
            self.scale = [None for _ in range(3)]
63
64
        self.w = [
            torch.rand(hidden_size, hidden_size).to(dtype=FP8_DTYPE).t()
65
            for _ in range(3)
66
        ]
67
68
69
70
71
72

        with override_cutlass_fp8_supported(not cuda_force_torch):
            self.fp8_linear = Fp8LinearOp(
                act_quant_static=static,
                act_quant_group_shape=group_shape,
            )
73

74
75
76
        self.enable_rms_norm_custom_op = self.norm[0].enabled()
        self.enable_quant_fp8_custom_op = self.fp8_linear.quant_fp8.enabled()

77
    def forward(self, x):
78
79
        # avoid having graph input be an arg to a pattern directly
        x = resid = torch.relu(x)
80
81
        y = self.norm[0](x)

82
83
84
        x2 = self.fp8_linear.apply(
            y, self.w[0], self.wscale[0], input_scale=self.scale[0]
        )
85
86
87
        # make sure resid is used for replacement to work
        y2, resid = self.norm[1](x2, resid)

88
89
90
        x3 = self.fp8_linear.apply(
            y2, self.w[1], self.wscale[1], input_scale=self.scale[1]
        )
91

92
93
        y3, resid = self.norm[2](x3, resid)  # use resid here

94
95
96
97
98
99
        x4 = self.fp8_linear.apply(
            y3, self.w[2], self.wscale[2], input_scale=self.scale[2]
        )

        y4, resid = self.norm[3](x4, resid)  # use resid here
        return y4
100
101
102

    def ops_in_model_after(self):
        return [
103
104
            FUSED_OPS[FusedRMSQuantKey(self.quant_key, True)],
            FUSED_OPS[FusedRMSQuantKey(self.quant_key, False)],
105
106
        ]

107
108
109
110
111
112
113
114
115
116
117
118
119
120
    def ops_in_model_before(self):
        return (
            [QUANT_OPS[self.quant_key]]
            if self.enable_quant_fp8_custom_op
            else [torch.ops.aten.reciprocal]
        )

    def ops_in_model_before_partial(self):
        return (
            [RMS_OP, RMS_ADD_OP]
            if self.enable_rms_norm_custom_op
            else [torch.ops.aten.rsqrt]
        )

121
122

@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
123
124
@pytest.mark.parametrize("hidden_size", [64])
@pytest.mark.parametrize("num_tokens", [257])
125
@pytest.mark.parametrize("eps", [1e-5, 1e-6])
126
@pytest.mark.parametrize("static", [True, False])
127
128
@pytest.mark.parametrize("enable_rms_norm_custom_op", [True, False])
@pytest.mark.parametrize("enable_quant_fp8_custom_op", [True, False])
129
130
# cuda_force_torch used to test torch code path on platforms that
# cutlass_fp8_supported() == True.
131
132
133
134
135
136
137
@pytest.mark.parametrize(
    "cuda_force_torch", [True, False] if cutlass_fp8_supported() else [True]
)
@pytest.mark.skipif(
    not current_platform.is_cuda_alike(), reason="Only test on CUDA and ROCm"
)
def test_fusion_rmsnorm_quant(
138
139
140
141
142
143
144
145
    dtype,
    hidden_size,
    num_tokens,
    eps,
    static,
    enable_rms_norm_custom_op,
    enable_quant_fp8_custom_op,
    cuda_force_torch,
146
):
147
    torch.set_default_device("cuda")
148
149
    torch.set_default_dtype(dtype)
    torch.manual_seed(1)
150
    maybe_create_device_identity()  # needed for certain non-cutlass fp8 paths
151

152
153
154
155
156
    custom_ops = []
    if enable_rms_norm_custom_op:
        custom_ops.append("+rms_norm")
    if enable_quant_fp8_custom_op:
        custom_ops.append("+quant_fp8")
157
    vllm_config = VllmConfig(
158
        model_config=ModelConfig(dtype=dtype),
159
        compilation_config=CompilationConfig(
160
            mode=CompilationMode.VLLM_COMPILE,
161
            custom_ops=custom_ops,
162
163
164
            pass_config=PassConfig(
                fuse_norm_quant=True, fuse_act_quant=True, eliminate_noops=True
            ),
165
        ),
166
    )
167
168
    with vllm.config.set_current_vllm_config(vllm_config):
        # Reshape pass is needed for the fusion pass to work
169
        noop_pass = NoOpEliminationPass(vllm_config)
170
171
        fusion_pass = RMSNormQuantFusionPass(vllm_config)
        cleanup_pass = PostCleanupPass(vllm_config)
172

173
        backend = TestBackend(noop_pass, fusion_pass, cleanup_pass)
174
        backend2 = TestBackend(noop_pass, cleanup_pass)
175
        model = TestModel(hidden_size, eps, static, cuda_force_torch)
176
177
178
179
180

        # First dimension dynamic
        x = torch.rand(num_tokens, hidden_size)
        torch._dynamo.mark_dynamic(x, 0)

181
182
        model_fused = torch.compile(model, backend=backend)
        result_fused = model_fused(x)
183

184
185
        model_unfused = torch.compile(model, backend=backend2)
        result_unfused = model_unfused(x)
186

187
        if dtype == torch.float16:
188
189
190
191
            ATOL, RTOL = (2e-3, 2e-3)
        else:
            ATOL, RTOL = (1e-2, 1e-2)

192
        torch.testing.assert_close(result_fused, result_unfused, atol=ATOL, rtol=RTOL)
193

194
        assert fusion_pass.matched_count == 3
195
        backend.check_before_ops(model.ops_in_model_before())
196
197
198
        backend.check_before_ops(
            model.ops_in_model_before_partial(), fully_replaced=False
        )
199
        backend.check_after_ops(model.ops_in_model_after())
200
201
202
203
204
205
206
207
208
209

        # If RMSNorm custom op is disabled (native/torch impl used),
        # there's a risk that the fused add doesn't get included in the
        # replacement and only the rms part gets fused with quant.
        # Hence, we check only 2 add nodes are left (final fused rmsnorm add).
        if not enable_rms_norm_custom_op:
            n_add_nodes = lambda g: sum(1 for _ in find_op_nodes(torch.ops.aten.add, g))
            # 7 = 1 (RMS) + 3x2 (3xRMS_ADD, 2 each)
            assert n_add_nodes(backend.graph_pre_pass) == 7
            assert n_add_nodes(backend.graph_post_pass) == 2