activation.py 6.13 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
Woosuk Kwon's avatar
Woosuk Kwon committed
14
15


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

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

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

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

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

34
35
36
        d = x.shape[-1] // 2
        output_shape = (x.shape[:-1] + (d, ))
        out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
37
        ops.silu_and_mul(out, x)
Woosuk Kwon's avatar
Woosuk Kwon committed
38
        return out
39
40


41
class GeluAndMul(CustomOp):
42
43
44
45
46
47
48
49
50
    """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)
    """

51
52
53
54
55
56
    def __init__(self, approximate: str = "none"):
        super().__init__()
        self.approximate = approximate
        if approximate not in ("none", "tanh"):
            raise ValueError(f"Unknown approximate mode: {approximate}")

57
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
58
59
        """PyTorch-native implementation equivalent to forward()."""
        d = x.shape[-1] // 2
60
        return F.gelu(x[..., :d], approximate=self.approximate) * x[..., d:]
61

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

65
66
67
        d = x.shape[-1] // 2
        output_shape = (x.shape[:-1] + (d, ))
        out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
68
69
70
71
        if self.approximate == "none":
            ops.gelu_and_mul(out, x)
        elif self.approximate == "tanh":
            ops.gelu_tanh_and_mul(out, x)
72
73
        return out

74
75
76
    def extra_repr(self) -> str:
        return f'approximate={repr(self.approximate)}'

77

78
class NewGELU(CustomOp):
79

80
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
81
82
83
84
85
        """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))))

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

89
        out = torch.empty_like(x)
90
        ops.gelu_new(out, x)
91
92
93
        return out


94
class FastGELU(CustomOp):
95

96
    def forward_native(self, x: torch.Tensor) -> torch.Tensor:
97
98
99
100
        """PyTorch-native implementation equivalent to forward()."""
        return 0.5 * x * (1.0 + torch.tanh(x * 0.7978845608 *
                                           (1.0 + 0.044715 * x * x)))

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

104
        out = torch.empty_like(x)
105
        ops.gelu_fast(out, x)
106
107
108
        return out


109
110
111
112
113
114
115
116
117
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,
118
119
120
        intermediate_size: int,
        input_is_parallel: bool = True,
        params_dtype: Optional[torch.dtype] = None,
121
122
123
    ):
        super().__init__()
        self.act = act_module
124
        self.input_is_parallel = input_is_parallel
125
126
127
128
129
130
131
132
        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()
133
        self.scales = nn.Parameter(
134
            torch.empty(intermediate_size_per_partition, dtype=params_dtype))
135
        set_weight_attrs(self.scales, {"weight_loader": self.weight_loader})
136

137
    def forward(self, x: torch.Tensor) -> torch.Tensor:
138
139
        return self.act(x) / self.scales

140
141
    def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor):
        param_data = param.data
142
143
144
145
146
        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)
147
148
149
        assert param_data.shape == loaded_weight.shape
        param_data.copy_(loaded_weight)

150

151
152
153
154
155
156
157
158
159
_ACTIVATION_REGISTRY = {
    "gelu": nn.GELU(),
    "gelu_fast": FastGELU(),
    "gelu_new": NewGELU(),
    "gelu_pytorch_tanh": nn.GELU(approximate="tanh"),
    "relu": nn.ReLU(),
}


160
161
162
163
def get_act_fn(
    act_fn_name: str,
    quant_config: Optional[QuantizationConfig] = None,
    intermediate_size: Optional[int] = None,
164
165
    input_is_parallel: bool = True,
    params_dtype: Optional[torch.dtype] = None,
166
) -> nn.Module:
167
    """Get an activation function by name."""
168
169
170
171
172
173
    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]
174
175
    if (quant_config is not None
            and act_fn_name in quant_config.get_scaled_act_names()):
176
177
178
        if intermediate_size is None:
            raise ValueError("intermediate_size must be specified for scaled "
                             "activation functions.")
179
180
        return ScaledActivation(act_fn, intermediate_size, input_is_parallel,
                                params_dtype)
181
    return act_fn