activation.py 8.72 KB
Newer Older
1
"""Custom activation functions."""
2
import math
3
4
from typing import Optional

Woosuk Kwon's avatar
Woosuk Kwon committed
5
6
import torch
import torch.nn as nn
7
import torch.nn.functional as F
Woosuk Kwon's avatar
Woosuk Kwon committed
8

9
10
from vllm.distributed import (divide, get_tensor_model_parallel_rank,
                              get_tensor_model_parallel_world_size)
11
from vllm.model_executor.custom_op import CustomOp
12
from vllm.model_executor.layers.quantization import QuantizationConfig
13
from vllm.model_executor.utils import set_weight_attrs
zhuwenwen's avatar
zhuwenwen committed
14
import vllm.envs as envs
Woosuk Kwon's avatar
Woosuk Kwon committed
15
16


17
class SiluAndMul(CustomOp):
18
19
    """An activation function for SwiGLU.

20
    The function computes x -> silu(x[:d]) * x[d:] where d = x.shape[-1] // 2.
Woosuk Kwon's avatar
Woosuk Kwon committed
21

22
    Shapes:
23
24
        x: (num_tokens, 2 * d) or (batch_size, seq_len, 2 * d)
        return: (num_tokens, d) or (batch_size, seq_len, d)
25
    """
Woosuk Kwon's avatar
Woosuk Kwon committed
26

27
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
28
29
30
31
        """PyTorch-native implementation equivalent to forward()."""
        d = x.shape[-1] // 2
        return F.silu(x[..., :d]) * x[..., d:]

32
33
34
    def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
        from vllm import _custom_ops as ops

35
36
37
        d = x.shape[-1] // 2
        output_shape = (x.shape[:-1] + (d, ))
        out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
zhuwenwen's avatar
zhuwenwen committed
38
39
40
41
        if envs.VLLM_USE_OPT_OP:
            ops.silu_and_mul_opt(out, x)
        else:
            ops.silu_and_mul(out, x)
Woosuk Kwon's avatar
Woosuk Kwon committed
42
        return out
43

44
45
46
47
48
49
50
51
52
    def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
        from vllm._ipex_ops import ipex_ops as ops

        d = x.shape[-1] // 2
        output_shape = (x.shape[:-1] + (d, ))
        out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
        ops.silu_and_mul(out, x)
        return out

53

54
class GeluAndMul(CustomOp):
55
56
57
58
59
60
61
62
63
    """An activation function for GeGLU.

    The function computes x -> GELU(x[:d]) * x[d:] where d = x.shape[-1] // 2.

    Shapes:
        x: (batch_size, seq_len, 2 * d) or (num_tokens, 2 * d)
        return: (batch_size, seq_len, d) or (num_tokens, d)
    """

64
65
66
67
68
69
    def __init__(self, approximate: str = "none"):
        super().__init__()
        self.approximate = approximate
        if approximate not in ("none", "tanh"):
            raise ValueError(f"Unknown approximate mode: {approximate}")

70
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
71
72
        """PyTorch-native implementation equivalent to forward()."""
        d = x.shape[-1] // 2
73
        return F.gelu(x[..., :d], approximate=self.approximate) * x[..., d:]
74

75
76
77
    def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
        from vllm import _custom_ops as ops

78
79
80
        d = x.shape[-1] // 2
        output_shape = (x.shape[:-1] + (d, ))
        out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
81
        if self.approximate == "none":
zhuwenwen's avatar
zhuwenwen committed
82
83
84
85
            if envs.VLLM_USE_OPT_OP:
                ops.gelu_and_mul_opt(out, x)
            else:
                ops.gelu_and_mul(out, x)
86
        elif self.approximate == "tanh":
zhuwenwen's avatar
zhuwenwen committed
87
88
89
90
            if envs.VLLM_USE_OPT_OP:
                ops.gelu_tanh_and_mul_opt(out, x)
            else:
                ops.gelu_tanh_and_mul(out, x)
91
92
        return out

93
94
95
96
97
98
99
100
101
102
103
104
    def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
        from vllm._ipex_ops import ipex_ops as ops

        d = x.shape[-1] // 2
        output_shape = (x.shape[:-1] + (d, ))
        out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
        if self.approximate == "none":
            ops.gelu_and_mul(out, x)
        elif self.approximate == "tanh":
            ops.gelu_tanh_and_mul(out, x)
        return out

105
106
107
    def extra_repr(self) -> str:
        return f'approximate={repr(self.approximate)}'

108

109
class NewGELU(CustomOp):
110

111
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
112
113
114
115
116
        """PyTorch-native implementation equivalent to forward()."""
        c = math.sqrt(2.0 / math.pi)
        return 0.5 * x * (1.0 + torch.tanh(c *
                                           (x + 0.044715 * torch.pow(x, 3.0))))

117
118
119
    def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
        from vllm import _custom_ops as ops

120
        out = torch.empty_like(x)
121
        ops.gelu_new(out, x)
122
123
        return out

124
125
126
    def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
        from vllm._ipex_ops import ipex_ops as ops

127
        return ops.gelu_new(x)
128

129

130
class FastGELU(CustomOp):
131

132
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
133
134
135
136
        """PyTorch-native implementation equivalent to forward()."""
        return 0.5 * x * (1.0 + torch.tanh(x * 0.7978845608 *
                                           (1.0 + 0.044715 * x * x)))

137
138
139
    def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
        from vllm import _custom_ops as ops

140
        out = torch.empty_like(x)
141
        ops.gelu_fast(out, x)
142
143
        return out

144
145
146
    def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
        from vllm._ipex_ops import ipex_ops as ops

147
        return ops.gelu_fast(x)
148

149

150
151
152
153
154
155
156
157
158
159
160
161
162
163
class QuickGELU(CustomOp):

    # https://github.com/huggingface/transformers/blob/main/src/transformers/activations.py#L90
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
        """PyTorch-native implementation equivalent to forward()."""
        return x * torch.sigmoid(1.702 * x)

    def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
        from vllm import _custom_ops as ops

        out = torch.empty_like(x)
        ops.gelu_quick(out, x)
        return out

164
165
166
167
168
169
170
    def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
        from vllm._ipex_ops import ipex_ops as ops

        out = torch.empty_like(x)
        ops.gelu_quick(out, x)
        return out

171
172
173
    # TODO implement forward_xpu for QuickGELU
    # def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:

174

175
176
177
178
179
180
181
class ReLUSquaredActivation(CustomOp):
    """
    Applies the relu^2 activation introduced in https://arxiv.org/abs/2109.08668v2
    """

    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
        """PyTorch-native implementation equivalent to forward()."""
182
        return torch.square(F.relu(x))
183
184
185
186
187

    def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
        return self.forward_native(x)


188
189
190
191
192
193
194
195
196
class ScaledActivation(nn.Module):
    """An activation function with post-scale parameters.

    This is used for some quantization methods like AWQ.
    """

    def __init__(
        self,
        act_module: nn.Module,
197
198
199
        intermediate_size: int,
        input_is_parallel: bool = True,
        params_dtype: Optional[torch.dtype] = None,
200
201
202
    ):
        super().__init__()
        self.act = act_module
203
        self.input_is_parallel = input_is_parallel
204
205
206
207
208
209
210
211
        if input_is_parallel:
            tp_size = get_tensor_model_parallel_world_size()
            intermediate_size_per_partition = divide(intermediate_size,
                                                     tp_size)
        else:
            intermediate_size_per_partition = intermediate_size
        if params_dtype is None:
            params_dtype = torch.get_default_dtype()
212
        self.scales = nn.Parameter(
213
            torch.empty(intermediate_size_per_partition, dtype=params_dtype))
214
        set_weight_attrs(self.scales, {"weight_loader": self.weight_loader})
215

216
    def forward(self, x: torch.Tensor) -> torch.Tensor:
217
218
        return self.act(x) / self.scales

219
220
    def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor):
        param_data = param.data
221
222
223
224
225
        if self.input_is_parallel:
            tp_rank = get_tensor_model_parallel_rank()
            shard_size = param_data.shape[0]
            start_idx = tp_rank * shard_size
            loaded_weight = loaded_weight.narrow(0, start_idx, shard_size)
226
227
228
        assert param_data.shape == loaded_weight.shape
        param_data.copy_(loaded_weight)

229

230
231
232
233
234
235
_ACTIVATION_REGISTRY = {
    "gelu": nn.GELU(),
    "gelu_fast": FastGELU(),
    "gelu_new": NewGELU(),
    "gelu_pytorch_tanh": nn.GELU(approximate="tanh"),
    "relu": nn.ReLU(),
236
    "relu2": ReLUSquaredActivation(),
237
    "quick_gelu": QuickGELU(),
238
239
240
}


241
242
243
244
def get_act_fn(
    act_fn_name: str,
    quant_config: Optional[QuantizationConfig] = None,
    intermediate_size: Optional[int] = None,
245
246
    input_is_parallel: bool = True,
    params_dtype: Optional[torch.dtype] = None,
247
) -> nn.Module:
248
    """Get an activation function by name."""
249
250
251
252
253
254
    act_fn_name = act_fn_name.lower()
    if act_fn_name not in _ACTIVATION_REGISTRY:
        raise ValueError(
            f"Activation function {act_fn_name!r} is not supported.")

    act_fn = _ACTIVATION_REGISTRY[act_fn_name]
255
256
    if (quant_config is not None
            and act_fn_name in quant_config.get_scaled_act_names()):
257
258
259
        if intermediate_size is None:
            raise ValueError("intermediate_size must be specified for scaled "
                             "activation functions.")
260
261
        return ScaledActivation(act_fn, intermediate_size, input_is_parallel,
                                params_dtype)
262
    return act_fn