custom_op.py 4.66 KB
Newer Older
1
2
3
from functools import lru_cache
from typing import Dict, Type

4
5
import torch.nn as nn

6
import vllm.envs as envs
7
from vllm.compilation.levels import CompilationLevel
8
from vllm.logger import init_logger
9
from vllm.platforms import current_platform
10
from vllm.utils import print_warning_once
11
12

logger = init_logger(__name__)
13
14
15


class CustomOp(nn.Module):
16
17
18
19
    """
    Base class for custom ops.
    Dispatches the forward method to the appropriate backend.
    """
20

21
    def __init__(self):
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
        super().__init__()
        self._forward_method = self.dispatch_forward()

    def forward(self, *args, **kwargs):
        return self._forward_method(*args, **kwargs)

    def forward_native(self, *args, **kwargs):
        """PyTorch-native implementation of the forward method.
        This method is optional. If implemented, it can be used with compilers
        such as torch.compile or PyTorch XLA. Also, it can be used for testing
        purposes.
        """
        raise NotImplementedError

    def forward_cuda(self, *args, **kwargs):
        raise NotImplementedError

    def forward_hip(self, *args, **kwargs):
        # By default, we assume that HIP ops are compatible with CUDA ops.
        return self.forward_cuda(*args, **kwargs)

    def forward_xpu(self, *args, **kwargs):
44
45
46
        # By default, we assume that XPU ops are compatible with the
        # PyTorch-native implementation.
        return self.forward_native(*args, **kwargs)
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

    def forward_cpu(self, *args, **kwargs):
        # By default, we assume that CPU ops are compatible with CUDA ops.
        return self.forward_cuda(*args, **kwargs)

    def forward_tpu(self, *args, **kwargs):
        # By default, we assume that TPU ops are compatible with the
        # PyTorch-native implementation.
        # NOTE(woosuk): This is a placeholder for future extensions.
        return self.forward_native(*args, **kwargs)

    def forward_gaudi(self, *args, **kwargs):
        # By default, we assume that Gaudi ops are compatible with the
        # PyTorch-native implementation.
        # NOTE(woosuk): This is a placeholder for future extensions.
        return self.forward_native(*args, **kwargs)

    def dispatch_forward(self):
        # NOTE(woosuk): Here we assume that vLLM was built for only one
        # specific backend. Currently, we do not support dynamic dispatching.
67

68
69
70
71
72
        enabled = self.enabled()
        logger.debug("custom op %s %s", self.__class__.name,
                     "enabled" if enabled else "disabled")

        if not enabled:
73
74
            return self.forward_native

75
        if current_platform.is_rocm():
76
            return self.forward_hip
77
        elif current_platform.is_cpu():
78
            return self.forward_cpu
79
        elif current_platform.is_tpu():
80
            return self.forward_tpu
81
        elif current_platform.is_xpu():
82
            return self.forward_xpu
83
84
        else:
            return self.forward_cuda
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102

    @classmethod
    def enabled(cls) -> bool:
        # if no name, then it was not registered
        if not hasattr(cls, "name"):
            print_warning_once(
                f"Custom op {cls.__name__} was not registered, "
                f"which means it won't appear in the op registry. "
                f"It will be enabled/disabled based on the global settings.")
            return CustomOp.default_on()

        enabled = f"+{cls.name}" in envs.VLLM_CUSTOM_OPS
        disabled = f"-{cls.name}" in envs.VLLM_CUSTOM_OPS
        assert not (enabled
                    and disabled), f"Cannot enable and disable {cls.name}"

        return (CustomOp.default_on() or enabled) and not disabled

103
    # On by default if VLLM_TORCH_COMPILE_LEVEL < CompilationLevel.PIECEWISE
104
105
106
107
108
109
110
    # Specifying 'all' or 'none' in VLLM_CUSTOM_OPS takes precedence.
    @staticmethod
    @lru_cache()
    def default_on() -> bool:
        count_none = envs.VLLM_CUSTOM_OPS.count("none")
        count_all = envs.VLLM_CUSTOM_OPS.count("all")
        assert count_none + count_all <= 1, "Can only specify 'none' or 'all'"
111
        return envs.VLLM_TORCH_COMPILE_LEVEL < CompilationLevel.PIECEWISE and \
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
            not count_none > 0 or count_all > 0

    # Dictionary of all custom ops (classes, indexed by registered name).
    # To check if an op with a name is enabled, call .enabled() on the class.
    # Examples:
    # - MyOp.enabled()
    # - op_registry["my_op"].enabled()
    op_registry: Dict[str, Type['CustomOp']] = {}

    # Decorator to register custom ops.
    @classmethod
    def register(cls, name: str):

        def decorator(op_cls):
            assert name not in cls.op_registry, f"Duplicate op name: {name}"
            op_cls.name = name
            cls.op_registry[name] = op_cls
            return op_cls

        return decorator