activation_quant_fusion.py 6.75 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
    QuantKey,
    kFp8StaticTensorSym,
21
    kNvfp4Dynamic,
22
)
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[kNvfp4Dynamic] = 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
        super().__init__(kNvfp4Dynamic)
133

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
                output_scale=output_scale,
                input_scale=scale,
155
                is_sf_swizzled_layout=True,
156
            )
157
            return at[1], at[2]
158

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

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


177
class ActivationQuantFusionPass(VllmPatternMatcherPass):
178
179
180
181
182
183
184
185
186
    """
    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
    """

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

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

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

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

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

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

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