|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | + |
| 4 | +import inspect |
| 5 | +from typing import TypeVar, Union |
| 6 | +from unittest.mock import patch |
| 7 | + |
| 8 | +import torch |
| 9 | +import torch.nn as nn |
| 10 | +from torch._dynamo.symbolic_convert import InliningInstructionTranslator |
| 11 | +from vllm.compilation import decorators |
| 12 | +from vllm.compilation.counter import compilation_counter |
| 13 | +from vllm.compilation.monitor import start_monitoring_torch_compile |
| 14 | +from vllm.compilation.wrapper import TorchCompileWrapperWithCustomDispatcher |
| 15 | +from vllm.config import CompilationLevel, VllmConfig |
| 16 | +from vllm.forward_context import get_forward_context |
| 17 | +from vllm.logger import init_logger |
| 18 | +from vllm.sequence import IntermediateTensors |
| 19 | +from vllm.utils import supports_dynamo |
| 20 | + |
| 21 | +from vllm_ascend.attention.attention_v1 import AscendAttentionState |
| 22 | + |
| 23 | +logger = init_logger(__name__) |
| 24 | + |
| 25 | +_T = TypeVar("_T", bound=type[nn.Module]) |
| 26 | + |
| 27 | + |
| 28 | +def _ascend_support_torch_compile( |
| 29 | + cls: _T, |
| 30 | + dynamic_arg_dims: dict[str, Union[int, list[int]]], |
| 31 | +) -> _T: |
| 32 | + """ |
| 33 | + A decorator to add support for compiling the forward method of a class. |
| 34 | + """ |
| 35 | + if TorchCompileWrapperWithCustomDispatcher in cls.__bases__: |
| 36 | + # support decorating multiple times |
| 37 | + return cls |
| 38 | + |
| 39 | + # take care of method resolution order |
| 40 | + # make sure super().__init__ is called on the base class |
| 41 | + # other than TorchCompileWrapperWithCustomDispatcher |
| 42 | + cls.__bases__ = cls.__bases__ + (TorchCompileWrapperWithCustomDispatcher, ) |
| 43 | + |
| 44 | + old_init = cls.__init__ |
| 45 | + |
| 46 | + def __init__(self, *, vllm_config: VllmConfig, prefix: str = '', **kwargs): |
| 47 | + old_init(self, vllm_config=vllm_config, prefix=prefix, **kwargs) |
| 48 | + self.vllm_config = vllm_config |
| 49 | + # for CompilationLevel.DYNAMO_AS_IS , the upper level model runner |
| 50 | + # will handle the compilation, so we don't need to do anything here. |
| 51 | + self.do_not_compile = \ |
| 52 | + vllm_config.compilation_config.level in [ |
| 53 | + CompilationLevel.NO_COMPILATION, CompilationLevel.DYNAMO_AS_IS |
| 54 | + ] or not supports_dynamo() |
| 55 | + if self.do_not_compile: |
| 56 | + return |
| 57 | + compilation_counter.num_models_seen += 1 |
| 58 | + TorchCompileWrapperWithCustomDispatcher.__init__( |
| 59 | + self, compilation_level=vllm_config.compilation_config.level) |
| 60 | + |
| 61 | + cls.__init__ = __init__ |
| 62 | + |
| 63 | + def __call__(self, *args, **kwargs): |
| 64 | + # torch.compiler.is_compiling() means we are inside the compilation |
| 65 | + # e.g. TPU has the compilation logic in model runner, so we don't |
| 66 | + # need to compile the model inside. |
| 67 | + attn_metadata = get_forward_context().attn_metadata |
| 68 | + if attn_metadata is not None and attn_metadata.attn_state != AscendAttentionState.DecodeOnly: |
| 69 | + return self.forward(*args, **kwargs) |
| 70 | + |
| 71 | + if self.do_not_compile or torch.compiler.is_compiling(): |
| 72 | + return self.forward(*args, **kwargs) |
| 73 | + |
| 74 | + # the first compilation needs to have dynamic shapes marked |
| 75 | + if len(self.compiled_codes) < 1: |
| 76 | + sig = inspect.signature(self.__class__.forward) |
| 77 | + bound_args = sig.bind(self, *args, **kwargs) |
| 78 | + bound_args.apply_defaults() |
| 79 | + for k, dims in dynamic_arg_dims.items(): |
| 80 | + arg = bound_args.arguments.get(k) |
| 81 | + if arg is not None: |
| 82 | + dims = [dims] if isinstance(dims, int) else dims |
| 83 | + if isinstance(arg, torch.Tensor): |
| 84 | + # In case dims is specified with negative indexing |
| 85 | + dims = [ |
| 86 | + arg.ndim + dim if dim < 0 else dim for dim in dims |
| 87 | + ] |
| 88 | + torch._dynamo.mark_dynamic(arg, dims) |
| 89 | + elif isinstance(arg, IntermediateTensors): |
| 90 | + for tensor in arg.tensors.values(): |
| 91 | + # In case dims is specified with negative indexing |
| 92 | + dims = [ |
| 93 | + tensor.ndim + dim if dim < 0 else dim |
| 94 | + for dim in dims |
| 95 | + ] |
| 96 | + torch._dynamo.mark_dynamic(tensor, dims) |
| 97 | + else: |
| 98 | + raise ValueError( |
| 99 | + "Unsupported dynamic dimensions" |
| 100 | + f" {dims} for argument {k} with type {type(arg)}.") |
| 101 | + # here, it is the starting point of the `torch.compile` process |
| 102 | + start_monitoring_torch_compile(self.vllm_config) |
| 103 | + logger.debug("Start compiling function %s", |
| 104 | + self.original_code_object) |
| 105 | + |
| 106 | + # if we don't use custom dispatcher, we can directly call the |
| 107 | + # compiled function and let torch.compile handle the dispatching, |
| 108 | + # with the overhead of guard evaluation and recompilation. |
| 109 | + if len(self.compiled_codes) < 1 or not self.use_custom_dispatcher: |
| 110 | + # it seems Dynamo reuse the compilation across instances, |
| 111 | + # while we need to make sure the compiled code is not reused. |
| 112 | + # we need to control all the compilation of the model. |
| 113 | + torch._dynamo.eval_frame.remove_from_cache( |
| 114 | + self.original_code_object) |
| 115 | + |
| 116 | + # collect all relevant files traced by Dynamo, |
| 117 | + # so that the compilation cache can trigger re-compilation |
| 118 | + # properly when any of these files change. |
| 119 | + |
| 120 | + # 1. the file containing the top-level forward function |
| 121 | + self.vllm_config.compilation_config.traced_files.add( |
| 122 | + self.original_code_object.co_filename) |
| 123 | + |
| 124 | + # 2. every time Dynamo sees a function call, it will inline |
| 125 | + # the function by calling InliningInstructionTranslator.inline_call |
| 126 | + # we hijack this function to know all the functions called |
| 127 | + # during Dynamo tracing, and their corresponding files |
| 128 | + inline_call = InliningInstructionTranslator.inline_call |
| 129 | + |
| 130 | + def patched_inline_call(parent, func, args, kwargs): |
| 131 | + code = func.get_code() |
| 132 | + self.vllm_config.compilation_config.traced_files.add( |
| 133 | + code.co_filename) |
| 134 | + return inline_call(parent, func, args, kwargs) |
| 135 | + |
| 136 | + with patch.object(InliningInstructionTranslator, 'inline_call', |
| 137 | + patched_inline_call): |
| 138 | + output = self.compiled_callable(*args, **kwargs) |
| 139 | + return output |
| 140 | + |
| 141 | + # usually, capturing the model once is enough, and then we can |
| 142 | + # dispatch to the compiled code directly, without going through |
| 143 | + # the Dynamo guard mechanism. |
| 144 | + with self.dispatch_to_code(0): |
| 145 | + model_output = self.forward(*args, **kwargs) |
| 146 | + return model_output |
| 147 | + |
| 148 | + cls.__call__ = __call__ |
| 149 | + return cls |
| 150 | + |
| 151 | + |
| 152 | +decorators._support_torch_compile = _ascend_support_torch_compile |
0 commit comments