decorators.py 9.97 KB
Newer Older
1
import inspect
2
from typing import Callable, Dict, List, Optional, TypeVar, Union, overload
3
from unittest.mock import patch
4
5

import torch
6
import torch.nn as nn
7
from torch._dynamo.symbolic_convert import InliningInstructionTranslator
8

9
from vllm.compilation.counter import compilation_counter
10
from vllm.compilation.wrapper import TorchCompileWrapperWithCustomDispatcher
11
from vllm.config import CompilationLevel, VllmConfig
12
from vllm.logger import init_logger
13
14
15
from vllm.sequence import IntermediateTensors
from vllm.utils import supports_dynamo

16
17
from .monitor import start_monitoring_torch_compile

18
logger = init_logger(__name__)
19

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
_T = TypeVar("_T", bound=type[nn.Module])


@overload
def support_torch_compile(
    *,
    dynamic_arg_dims: Optional[Dict[str, Union[int, List[int]]]],
) -> Callable[[_T], _T]:
    ...


@overload
def support_torch_compile(cls: _T) -> _T:
    ...

35
36

def support_torch_compile(
37
38
39
40
    cls: Optional[_T] = None,
    *,
    dynamic_arg_dims: Optional[Dict[str, Union[int, List[int]]]] = None,
) -> Union[Callable[[_T], _T], _T]:
41
42
43
    """
    A decorator to add support for compiling the forward method of a class.

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    Usage 1: use directly as a decorator without arguments:

    ```python
    @support_torch_compile
    class MyModel(nn.Module):
        def forward(self, x: torch.Tensor, y: Optional[torch.Tensor]):
            ...
    ```

    Usage 2: use as a decorator with arguments:

    ```python
    @support_torch_compile(dynamic_arg_dims={"x": 0, "y": 0})
    class MyModel(nn.Module):
        def forward(self, x: torch.Tensor, y: Optional[torch.Tensor]):
            ...
    ```

62
63
64
65
    `dynamic_arg_dims` is a dictionary that maps argument names to the dynamic
    dimensions of the argument. The dynamic dimensions can be either a single
    integer or a list of integers.

66
67
68
69
70
71
72
73
74
75
76
77
    if `dynamic_arg_dims` is `None`, it is inferred from the type annotation
    of the `forward` method, based on the following default rules:

    - if the argument is annotated as `torch.Tensor` or
        `Optional[torch.Tensor]`, the first dimension will be
        marked as dynamic.
    - if the argument is annotated as `IntermediateTensors`, the first
        dimension of all the tensors in the intermediate tensors
        will be marked as dynamic.

    During runtime, when we actually mark dimensions of tensors,
     it depends on the value of arguments:
78

79
80
    - if it is a single integer (can be negative), the corresponding dimension 
        of the argument will be marked as dynamic.
81
82
83
84
85
86
87
88
89
90
    - if it is `None`, ignored.
    - if it is `IntermediateTensors`, all the tensors in the intermediate
        tensors will be marked as dynamic.
    - otherwise, it will raise an error.

    NOTE: if an argument is `None`, it should always be passed as `None` during
    the lifetime of the model, otherwise, it cannot be captured as a single
    computation graph.
    """

91
    def cls_decorator_helper(cls: _T) -> _T:
92
93
        # helper to pass `dynamic_arg_dims`` to `_support_torch_compile``
        # to avoid too much indentation for `_support_torch_compile``
94
95
        if not hasattr(cls, 'forward'):
            raise TypeError("decorated class should have a forward method.")
96
        sig = inspect.signature(cls.forward)
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        inferred_dynamic_arg_dims = dynamic_arg_dims
        if inferred_dynamic_arg_dims is None:
            inferred_dynamic_arg_dims = {}
            for k, v in sig.parameters.items():
                if v.annotation in [
                        torch.Tensor, Optional[torch.Tensor],
                        IntermediateTensors, Optional[IntermediateTensors]
                ]:
                    inferred_dynamic_arg_dims[k] = 0

            logger.debug(("Inferred dynamic dimensions for "
                          "forward method of %s: %s"), cls,
                         list(inferred_dynamic_arg_dims.keys()))

        if len(inferred_dynamic_arg_dims) == 0:
            raise ValueError(
                "No dynamic dimensions found in the forward method of "
                f"{cls}. Please provide dynamic_arg_dims explicitly.")

        for k in inferred_dynamic_arg_dims:
117
118
119
            if k not in sig.parameters:
                raise ValueError(
                    f"Argument {k} not found in the forward method of {cls}")
120
121
122
123
124
125
        return _support_torch_compile(cls, inferred_dynamic_arg_dims)

    if cls is not None:
        # use `support_torch_compile` as a decorator without arguments
        assert isinstance(cls, type)
        return cls_decorator_helper(cls)
126
127
128
129

    return cls_decorator_helper


130
131
132
133
def _support_torch_compile(
    cls: _T,
    dynamic_arg_dims: Dict[str, Union[int, List[int]]],
) -> _T:
134
135
136
    """
    A decorator to add support for compiling the forward method of a class.
    """
137
138
    if TorchCompileWrapperWithCustomDispatcher in cls.__bases__:
        # support decorating multiple times
139
140
141
142
143
        return cls

    # take care of method resolution order
    # make sure super().__init__ is called on the base class
    #  other than TorchCompileWrapperWithCustomDispatcher
144
    cls.__bases__ = cls.__bases__ + (TorchCompileWrapperWithCustomDispatcher, )
145

146
    old_init = cls.__init__
147

148
149
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = '', **kwargs):
        old_init(self, vllm_config=vllm_config, prefix=prefix, **kwargs)
150
        self.vllm_config = vllm_config
151
152
        # for CompilationLevel.DYNAMO_AS_IS , the upper level model runner
        # will handle the compilation, so we don't need to do anything here.
153
154
        self.do_not_compile = \
            vllm_config.compilation_config.level in [
155
156
157
158
            CompilationLevel.NO_COMPILATION, CompilationLevel.DYNAMO_AS_IS
        ] or not supports_dynamo()
        if self.do_not_compile:
            return
159
        compilation_counter.num_models_seen += 1
160
161
        TorchCompileWrapperWithCustomDispatcher.__init__(
            self, compilation_level=vllm_config.compilation_config.level)
162

163
    cls.__init__ = __init__
164

165
    def __call__(self, *args, **kwargs):
166
167
168
        # torch.compiler.is_compiling() means we are inside the compilation
        # e.g. TPU has the compilation logic in model runner, so we don't
        # need to compile the model inside.
169
        if self.do_not_compile or torch.compiler.is_compiling():
170
            return self.forward(*args, **kwargs)
171
172
173

        # the first compilation needs to have dynamic shapes marked
        if len(self.compiled_codes) < 1:
174
175
176
177
178
179
            sig = inspect.signature(self.__class__.forward)
            bound_args = sig.bind(self, *args, **kwargs)
            bound_args.apply_defaults()
            for k, dims in dynamic_arg_dims.items():
                arg = bound_args.arguments.get(k)
                if arg is not None:
180
                    dims = [dims] if isinstance(dims, int) else dims
181
                    if isinstance(arg, torch.Tensor):
182
183
184
185
                        # In case dims is specified with negative indexing
                        dims = [
                            arg.ndim + dim if dim < 0 else dim for dim in dims
                        ]
186
187
188
                        torch._dynamo.mark_dynamic(arg, dims)
                    elif isinstance(arg, IntermediateTensors):
                        for tensor in arg.tensors.values():
189
190
191
192
193
                            # In case dims is specified with negative indexing
                            dims = [
                                tensor.ndim + dim if dim < 0 else dim
                                for dim in dims
                            ]
194
195
196
197
198
                            torch._dynamo.mark_dynamic(tensor, dims)
                    else:
                        raise ValueError(
                            "Unsupported dynamic dimensions"
                            f" {dims} for argument {k} with type {type(arg)}.")
199
            # here, it is the starting point of the `torch.compile` process
200
            start_monitoring_torch_compile(self.vllm_config)
201
202
            logger.debug("Start compiling function %s",
                         self.original_code_object)
203
204
205
206
207

        # if we don't use custom dispatcher, we can directly call the
        # compiled function and let torch.compile handle the dispatching,
        # with the overhead of guard evaluation and recompilation.
        if len(self.compiled_codes) < 1 or not self.use_custom_dispatcher:
208
209
210
211
212
            # it seems Dynamo reuse the compilation across instances,
            # while we need to make sure the compiled code is not reused.
            # we need to control all the compilation of the model.
            torch._dynamo.eval_frame.remove_from_cache(
                self.original_code_object)
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

            # collect all relevant files traced by Dynamo,
            # so that the compilation cache can trigger re-compilation
            # properly when any of these files change.

            # 1. the file containing the top-level forward function
            self.vllm_config.compilation_config.traced_files.add(
                self.original_code_object.co_filename)

            # 2. every time Dynamo sees a function call, it will inline
            # the function by calling InliningInstructionTranslator.inline_call
            # we hijack this function to know all the functions called
            # during Dynamo tracing, and their corresponding files
            inline_call = InliningInstructionTranslator.inline_call

            def patched_inline_call(parent, func, args, kwargs):
                code = func.get_code()
                self.vllm_config.compilation_config.traced_files.add(
                    code.co_filename)
                return inline_call(parent, func, args, kwargs)

            with patch.object(InliningInstructionTranslator, 'inline_call',
                              patched_inline_call):
                output = self.compiled_callable(*args, **kwargs)
            return output
238
239
240
241
242

        # usually, capturing the model once is enough, and then we can
        # dispatch to the compiled code directly, without going through
        # the Dynamo guard mechanism.
        with self.dispatch_to_code(0):
243
            model_output = self.forward(*args, **kwargs)
244
245
            return model_output

246
    cls.__call__ = __call__
247
    return cls