pass_manager.py 7.47 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import functools
4
5
from collections.abc import Callable
from typing import Any, ParamSpec, TypeVar
6

7
8
from torch import fx as fx

9
from vllm import envs
10
from vllm._aiter_ops import rocm_aiter_ops
11
from vllm.compilation.passes.utility.post_cleanup import PostCleanupPass
12
from vllm.config import VllmConfig, set_current_vllm_config
13
from vllm.logger import init_logger
14
from vllm.platforms import current_platform
15
from vllm.utils.system_utils import set_env_var
16

17
from .ir.lowering_pass import VllmIRLoweringPass
18
from .vllm_inductor_pass import VllmInductorPass, VllmPatternMatcherPass
19

20
if rocm_aiter_ops.is_enabled():
21
    from .fusion.rocm_aiter_fusion import (
22
        RocmAiterRMSNormQuantFusionPass,
23
        RocmAiterSiluMulFp8GroupQuantFusionPass,
24
        RocmAiterTritonAddRMSNormPadFusionPass,
25
26
    )

27
if current_platform.is_cuda_alike():
28
    from .fusion.act_quant_fusion import ActivationQuantFusionPass
29
    from .fusion.attn_quant_fusion import AttnQuantFusionPass
30
31
    from .fusion.qk_norm_rope_fusion import QKNormRoPEFusionPass
    from .fusion.rms_quant_fusion import RMSNormQuantFusionPass
32
    from .fusion.rope_kvcache_fusion import RopeKVCacheFusionPass
33
    from .fusion.sequence_parallelism import SequenceParallelismPass
34
    from .utility.scatter_split_replace import ScatterSplitReplacementPass
35
    from .utility.split_coalescing import SplitCoalescingPass
36

37
if current_platform.is_cuda():
38
39
    from .fusion.allreduce_rms_fusion import AllReduceFusionPass
    from .fusion.collective_fusion import AsyncTPPass
40

41
42
43
44
45
from .inductor_pass import (
    CustomGraphPass,
    InductorPass,
    get_pass_context,
)
46
47
from .utility.fix_functionalization import FixFunctionalizationPass
from .utility.noop_elimination import NoOpEliminationPass
48
49
50

logger = init_logger(__name__)

51
52
P = ParamSpec("P")
R = TypeVar("R")
53

54
55

def with_pattern_match_debug(fn: Callable[P, R]) -> Callable[P, R]:
56
57
58
59
60
61
62
    """
    Function decorator that turns on inductor pattern match debug
    for the duration of the call.
    Used to avoid logging builtin Inductor pattern matching.
    """

    @functools.wraps(fn)
63
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
64
65
66
67
68
69
70
71
72
        if (debug_val := envs.VLLM_PATTERN_MATCH_DEBUG) is not None:
            # optionally check rank here
            with set_env_var("TORCHINDUCTOR_PATTERN_MATCH_DEBUG", debug_val):
                return fn(*args, **kwargs)
        return fn(*args, **kwargs)

    return wrapper


73
class PostGradPassManager(CustomGraphPass):  # type: ignore[misc]
74
75
76
    """
    The pass manager for post-grad passes.
    It handles configuration, adding custom passes, and running passes.
77
78
    It supports uuid for the Inductor code cache. That includes torch<2.6
    support using pickling (in .inductor_pass.CustomGraphPass).
79
80
81

    The order of the post-grad post-passes is:
    1. passes (constructor parameter)
82
    2. default passes (NoopEliminationPass, FusionPass)
83
84
85
86
87
    3. config["post_grad_custom_post_pass"] (if it exists)
    4. fix_functionalization
    This way, all passes operate on a functionalized graph.
    """

88
    def __init__(self) -> None:
89
        self.passes: list[InductorPass] = []
90

91
    @with_pattern_match_debug
92
    def __call__(self, graph: fx.Graph) -> None:
93
94
        VllmInductorPass.dump_prefix = 0  # reset dump index

95
        compile_range = get_pass_context().compile_range
96
        for pass_ in self.passes:
97
            if pass_.is_applicable_for_range(compile_range):
98
                pass_(graph)
99
                VllmInductorPass.dump_prefix += 1
100
            else:
101
                logger.debug("Skipping %s with compile range %s", pass_, compile_range)
102

103
104
105
106
107
108
109
110
111
112
113
        # perform the first post-cleanup before IR lowering to clean up fusion artifacts
        # and make sure no dead IR ops are lowered.
        self.post_cleanup(graph)
        VllmInductorPass.dump_prefix += 1

        # lowering before cleanup so DCE can clean up lowered ops.
        # DCE handles mutating ops correctly as well.
        self.ir_lowering(graph)
        VllmInductorPass.dump_prefix += 1

        # clean up after lowering again
114
115
        self.post_cleanup(graph)
        VllmInductorPass.dump_prefix += 1
116
117
118

        # always run fix_functionalization last
        self.fix_functionalization(graph)
119
        VllmInductorPass.dump_prefix = None  # Cleanup index
120

121
122
        VllmPatternMatcherPass.log_match_summary()

123
    def configure(self, config: VllmConfig) -> None:
124
        self.pass_config = config.compilation_config.pass_config
125

126
127
        # Set the current vllm config to allow tracing CustomOp instances
        with set_current_vllm_config(config, check_compile=False):
128
            if self.pass_config.eliminate_noops:
129
                self.passes += [NoOpEliminationPass(config)]
130

131
            if self.pass_config.enable_sp:
132
                self.passes += [SequenceParallelismPass(config)]
133
                if self.pass_config.fuse_gemm_comms:
134
                    self.passes += [AsyncTPPass(config)]
135

136
            if self.pass_config.fuse_allreduce_rms:
137
                self.passes += [AllReduceFusionPass(config)]
138

139
            if self.pass_config.fuse_norm_quant:
140
                self.passes += [RMSNormQuantFusionPass(config)]
141
                if rocm_aiter_ops.is_enabled():
142
                    self.passes += [
143
                        RocmAiterRMSNormQuantFusionPass(config),
144
                    ]
145
            if self.pass_config.fuse_act_quant:
146
                self.passes += [ActivationQuantFusionPass(config)]
147
148
                if rocm_aiter_ops.is_enabled():
                    self.passes += [RocmAiterSiluMulFp8GroupQuantFusionPass(config)]
149

150
151
152
            if self.pass_config.fuse_act_padding and rocm_aiter_ops.is_enabled():
                self.passes += [RocmAiterTritonAddRMSNormPadFusionPass(config)]

153
154
155
156
157
            if self.pass_config.fuse_rope_kvcache:
                self.passes += [SplitCoalescingPass(config)]
                self.passes += [ScatterSplitReplacementPass(config)]
                self.passes += [RopeKVCacheFusionPass(config)]

158
            if self.pass_config.fuse_attn_quant:
159
                self.passes += [AttnQuantFusionPass(config)]
160

161
            if self.pass_config.enable_qk_norm_rope_fusion:
162
                self.passes += [SplitCoalescingPass(config)]
163
164
                self.passes += [QKNormRoPEFusionPass(config)]

165
            self.ir_lowering = VllmIRLoweringPass(config)
166
167
            self.post_cleanup = PostCleanupPass(config)
            self.fix_functionalization = FixFunctionalizationPass(config)
168

169
    def add(self, pass_: InductorPass) -> None:
170
171
172
        assert isinstance(pass_, InductorPass)
        self.passes.append(pass_)

173
    def uuid(self) -> str:
174
        """
175
176
177
        The PostGradPassManager is set as a custom pass in the Inductor and
        affects compilation caching. Its uuid depends on the UUIDs of all
        dependent passes and the pass config. See InductorPass for more info.
178
        """
179
180
181
        passes = []

        state: dict[str, Any] = {"pass_config": self.pass_config.compute_hash()}
182
        for pass_ in self.passes:
183
            passes.append(pass_.uuid())
184
185
186
187

        passes.append(self.post_cleanup.uuid())
        passes.append(self.ir_lowering.uuid())
        passes.append(self.post_cleanup.uuid())
188
        passes.append(self.fix_functionalization.uuid())
189

190
191
192
        # Include the compile range in the uuid to ensure that inductor
        # recompiles the graph for the new dynamic compile range.
        state["compile_range"] = str(get_pass_context().compile_range)
193
        state["passes"] = passes
194
        return InductorPass.hash_dict(state)