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

4
from abc import ABC, abstractmethod
5
from typing import Any
6

7
8
import torch
from torch._higher_order_ops.auto_functionalize import auto_functionalized
9
10
11
12
13
from torch._inductor.pattern_matcher import (
    PatternMatcherPass,
    fwd_only,
    register_replacement,
)
14
from torch._ops import OpOverload
15
16
17

from vllm.config import VllmConfig
from vllm.logger import init_logger
18
from vllm.model_executor.layers.quantization.utils.quant_utils import (
19
20
21
22
    QuantKey,
    kFp8StaticTensorSym,
    kNvfp4Quant,
)
23
from vllm.platforms import current_platform
24

25
from .fusion import QUANT_OPS, empty_bf16, empty_fp32, empty_i32
26
from .inductor_pass import enable_fake_mode
27
from .matcher_utils import MatcherQuantFP8, MatcherSiluAndMul
28
from .vllm_inductor_pass import VllmInductorPass, VllmPatternMatcherPass
29
30
31

logger = init_logger(__name__)

32
33
34
35
FP8_DTYPE = current_platform.fp8_dtype()
FP4_DTYPE = torch.uint8

SILU_MUL_OP = torch.ops._C.silu_and_mul.default
36

37
38
39
# FUSED_OPS: dict[QuantKey, OpOverload] = {
#     kFp8StaticTensorSym: torch.ops._C.silu_and_mul_quant.default,  # noqa: E501
# }
40
41
42
# silu_and_mul_nvfp4_quant_supported = current_platform.is_cuda() and hasattr(
#     torch.ops._C, "silu_and_mul_nvfp4_quant"
# )
43
# if silu_and_mul_nvfp4_quant_supported:
44
#     FUSED_OPS[kNvfp4Quant] = torch.ops._C.silu_and_mul_nvfp4_quant.default  # noqa: E501
45
46


47
48
49
50
51
class ActivationQuantPattern(ABC):
    """
    The base class for Activation+Quant fusions.
    Should not be used directly.
    """
52

53
54
55
    def __init__(
        self,
        quant_key: QuantKey,
56
    ) -> None:
57
58
        self.quant_key = quant_key
        self.quant_dtype = quant_key.dtype
59

60
        assert self.quant_key in QUANT_OPS, (
61
            f"unsupported quantization scheme {self.quant_key}"
62
        )
63
        self.QUANT_OP = QUANT_OPS[self.quant_key]
64

65
        assert self.quant_key in FUSED_OPS, (
66
            f"unsupported fusion scheme {self.quant_key}"
67
        )
68
        self.FUSED_OP = FUSED_OPS[self.quant_key]
69

70
71
        self.silu_and_mul_matcher = MatcherSiluAndMul()

72
    def empty_quant(self, *args: Any, **kwargs: Any) -> torch.Tensor:
73
        kwargs = {"dtype": self.quant_dtype, "device": "cuda", **kwargs}
74
        return torch.empty(*args, **kwargs)
75

76
    @abstractmethod
77
    def register(self, pm_pass: PatternMatcherPass) -> None:
78
        raise NotImplementedError
79

80
81
82
83
84
85

class SiluMulFp8StaticQuantPattern(ActivationQuantPattern):
    """
    Fusion for SiluMul+Fp8StaticQuant Pattern
    """

86
    def __init__(self) -> None:
87
88
        super().__init__(kFp8StaticTensorSym)
        self.quant_matcher = MatcherQuantFP8(kFp8StaticTensorSym)
89

90
91
92
93
94
95
96
97
    def get_inputs(self) -> list[torch.Tensor]:
        scale = self.quant_matcher.inputs()[1]
        return [
            *self.silu_and_mul_matcher.inputs(),  # input
            scale,
        ]

    def register(self, pm_pass: PatternMatcherPass) -> None:
98
99
100
        def pattern(
            input: torch.Tensor,
            scale: torch.Tensor,
101
        ) -> torch.Tensor:
102
103
104
            result_silu_mul = self.silu_and_mul_matcher(input)
            result_quant = self.quant_matcher(result_silu_mul, scale)
            return result_quant[0]
105

106
107
108
        def replacement(
            input: torch.Tensor,
            scale: torch.Tensor,
109
        ) -> torch.Tensor:
110
111
112
113
114
            d = input.shape[-1] // 2
            output_shape = input.shape[:-1] + (d,)
            result = torch.empty(
                output_shape, device=input.device, dtype=self.quant_dtype
            )
115
116
117
            at = auto_functionalized(
                self.FUSED_OP, result=result, input=input, scale=scale
            )
118
119
            return at[1]

120
121
        inps = self.get_inputs()
        pattern(*inps)
122

123
        register_replacement(pattern, replacement, inps, fwd_only, pm_pass)
124
125
126
127
128
129
130


class SiluMulNvfp4QuantPattern(ActivationQuantPattern):
    """
    Fusion for SiluMul+Nvfp4Quant Pattern
    """

131
    def __init__(self) -> None:
132
133
        super().__init__(kNvfp4Quant)

134
135
136
137
138
139
140
141
    def get_inputs(self) -> list[torch.Tensor]:
        result = self.empty_quant(5, 32)
        output_scale = empty_i32(128, 4)
        input_ = empty_bf16(5, 64)
        scale = empty_fp32(1, 1)
        return [result, output_scale, input_, scale]

    def register(self, pm_pass: PatternMatcherPass) -> None:
142
143
144
145
146
        def pattern(
            result: torch.Tensor,
            output_scale: torch.Tensor,
            input: torch.Tensor,
            scale: torch.Tensor,
147
        ) -> tuple[torch.Tensor, torch.Tensor]:
148
149
            result_silu_mul = self.silu_and_mul_matcher(input)
            at = auto_functionalized(
150
151
                self.QUANT_OP,
                output=result,
152
                input=result_silu_mul,
153
154
155
                output_scale=output_scale,
                input_scale=scale,
            )
156
            return at[1], at[2]
157

158
159
160
161
162
        def replacement(
            result: torch.Tensor,
            output_scale: torch.Tensor,
            input: torch.Tensor,
            scale: torch.Tensor,
163
        ) -> tuple[torch.Tensor, torch.Tensor]:
164
165
166
167
168
169
170
            at = auto_functionalized(
                self.FUSED_OP,
                result=result,
                result_block_scale=output_scale,
                input=input,
                input_global_scale=scale,
            )
171
172
            return at[1], at[2]

173
        register_replacement(pattern, replacement, self.get_inputs(), fwd_only, pm_pass)
174
175


176
class ActivationQuantFusionPass(VllmPatternMatcherPass):
177
178
179
180
181
182
183
184
185
    """
    This pass fuses a pre-defined set of custom ops into fused ops.
    It uses the torch pattern matcher to find the patterns and replace them.

    Because patterns can only be registered once, the pass is a singleton.
    This will be addressed in a future version of PyTorch:
    https://github.com/pytorch/pytorch/pull/139321#issuecomment-2452354980
    """

186
    @enable_fake_mode
187
    def __init__(self, config: VllmConfig) -> None:
188
189
190
        super().__init__(config)

        self.patterns: PatternMatcherPass = PatternMatcherPass(
191
192
            pass_name="activation_quant_fusion_pass"
        )
193

194
195
196
        pattern_silu_mul_fp8 = SiluMulFp8StaticQuantPattern()
        pattern_silu_mul_fp8.register(self.patterns)

197
198
199
        if silu_and_mul_nvfp4_quant_supported:
            pattern_silu_mul_nvfp4 = SiluMulNvfp4QuantPattern()
            pattern_silu_mul_nvfp4.register(self.patterns)
200

201
        self.dump_patterns(config, self.patterns)
202

203
    @VllmInductorPass.time_and_log
204
    def __call__(self, graph: torch.fx.Graph) -> None:
205
206
        self.matched_count = self.patterns.apply(graph)
        logger.debug("Replaced %s patterns", self.matched_count)
207

208
    def uuid(self) -> str:
209
210
211
212
213
214
        return VllmInductorPass.hash_source(
            self,
            ActivationQuantPattern,
            SiluMulFp8StaticQuantPattern,
            SiluMulNvfp4QuantPattern,
        )