activation.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """Custom activation functions."""
  2. import math
  3. from typing import Optional
  4. import torch
  5. import torch.nn as nn
  6. import torch.nn.functional as F
  7. from aphrodite._C import ops
  8. from aphrodite.distributed import (divide, get_tensor_model_parallel_rank,
  9. get_tensor_model_parallel_world_size)
  10. from aphrodite.modeling.utils import set_weight_attrs
  11. from aphrodite.quantization import QuantizationConfig
  12. class SiluAndMul(nn.Module):
  13. """An activation function for SwiGLU.
  14. The function computes x -> silu(x[:d]) * x[d:] where d = x.shape[-1] // 2.
  15. Shapes:
  16. x: (num_tokens, 2 * d) or (batch_size, seq_len, 2 * d)
  17. return: (num_tokens, d) or (batch_size, seq_len, d)
  18. """
  19. def _forward(self, x: torch.Tensor) -> torch.Tensor:
  20. """PyTorch-native implementation equivalent to forward()."""
  21. d = x.shape[-1] // 2
  22. return F.silu(x[..., :d]) * x[..., d:]
  23. def forward(self, x: torch.Tensor) -> torch.Tensor:
  24. d = x.shape[-1] // 2
  25. output_shape = (x.shape[:-1] + (d, ))
  26. out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
  27. ops.silu_and_mul(out, x)
  28. return out
  29. class GeluAndMul(nn.Module):
  30. """An activation function for GeGLU.
  31. The function computes x -> GELU(x[:d]) * x[d:] where d = x.shape[-1] // 2.
  32. Shapes:
  33. x: (batch_size, seq_len, 2 * d) or (num_tokens, 2 * d)
  34. return: (batch_size, seq_len, d) or (num_tokens, d)
  35. """
  36. def __init__(self, approximate: str = "none"):
  37. super().__init__()
  38. self.approximate = approximate
  39. if approximate not in ("none", "tanh"):
  40. raise ValueError(f"Unknown approximate mode: {approximate}")
  41. def _forward(self, x: torch.Tensor) -> torch.Tensor:
  42. """PyTorch-native implementation equivalent to forward()."""
  43. d = x.shape[-1] // 2
  44. return F.gelu(x[..., :d], approximate=self.approximate) * x[..., d:]
  45. def forward(self, x: torch.Tensor) -> torch.Tensor:
  46. d = x.shape[-1] // 2
  47. output_shape = (x.shape[:-1] + (d, ))
  48. out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
  49. if self.approximate == "none":
  50. ops.gelu_and_mul(out, x)
  51. elif self.approximate == "tanh":
  52. ops.gelu_tanh_and_mul(out, x)
  53. return out
  54. class NewGELU(nn.Module):
  55. def _forward(self, x: torch.Tensor) -> torch.Tensor:
  56. """PyTorch-native implementation equivalent to forward()."""
  57. c = math.sqrt(2.0 / math.pi)
  58. return 0.5 * x * (1.0 + torch.tanh(c *
  59. (x + 0.044715 * torch.pow(x, 3.0))))
  60. def forward(self, x: torch.Tensor) -> torch.Tensor:
  61. out = torch.empty_like(x)
  62. ops.gelu_new(out, x)
  63. return out
  64. class FastGELU(nn.Module):
  65. def _forward(self, x: torch.Tensor) -> torch.Tensor:
  66. """PyTorch-native implementation equivalent to forward()."""
  67. return 0.5 * x * (1.0 + torch.tanh(x * 0.7978845608 *
  68. (1.0 + 0.044715 * x * x)))
  69. def forward(self, x: torch.Tensor) -> torch.Tensor:
  70. out = torch.empty_like(x)
  71. ops.gelu_fast(out, x)
  72. return out
  73. class ScaledActivation(nn.Module):
  74. """An activation function with post-scale parameters.
  75. This is used for some quantization methods like AWQ.
  76. """
  77. def __init__(
  78. self,
  79. act_module: nn.Module,
  80. intermediate_size: int,
  81. input_is_parallel: bool = True,
  82. params_dtype: Optional[torch.dtype] = None,
  83. ):
  84. super().__init__()
  85. self.act = act_module
  86. self.input_is_parallel = input_is_parallel
  87. if input_is_parallel:
  88. tp_size = get_tensor_model_parallel_world_size()
  89. intermediate_size_per_partition = divide(intermediate_size,
  90. tp_size)
  91. else:
  92. intermediate_size_per_partition = intermediate_size
  93. if params_dtype is None:
  94. params_dtype = torch.get_default_dtype()
  95. self.scales = nn.Parameter(
  96. torch.empty(intermediate_size_per_partition, dtype=params_dtype))
  97. set_weight_attrs(self.scales, {"weight_loader": self.weight_loader})
  98. def forward(self, x: torch.Tensor) -> torch.Tensor:
  99. return self.act(x) / self.scales
  100. def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor):
  101. param_data = param.data
  102. if self.input_is_parallel:
  103. tp_rank = get_tensor_model_parallel_rank()
  104. shard_size = param_data.shape[0]
  105. start_idx = tp_rank * shard_size
  106. loaded_weight = loaded_weight.narrow(0, start_idx, shard_size)
  107. assert param_data.shape == loaded_weight.shape
  108. param_data.copy_(loaded_weight)
  109. _ACTIVATION_REGISTRY = {
  110. "gelu": nn.GELU(),
  111. "gelu_fast": FastGELU(),
  112. "gelu_new": NewGELU(),
  113. "gelu_pytorch_tanh": nn.GELU(approximate="tanh"),
  114. "relu": nn.ReLU(),
  115. }
  116. def get_act_fn(
  117. act_fn_name: str,
  118. quant_config: Optional[QuantizationConfig] = None,
  119. intermediate_size: Optional[int] = None,
  120. input_is_parallel: bool = True,
  121. params_dtype: Optional[torch.dtype] = None,
  122. ) -> nn.Module:
  123. """Get an activation function by name."""
  124. act_fn_name = act_fn_name.lower()
  125. if act_fn_name not in _ACTIVATION_REGISTRY:
  126. raise ValueError(
  127. f"Activation function {act_fn_name!r} is not supported.")
  128. act_fn = _ACTIVATION_REGISTRY[act_fn_name]
  129. if (quant_config is not None
  130. and act_fn_name in quant_config.get_scaled_act_names()):
  131. if intermediate_size is None:
  132. raise ValueError("intermediate_size must be specified for scaled "
  133. "activation functions.")
  134. return ScaledActivation(act_fn, intermediate_size, input_is_parallel,
  135. params_dtype)
  136. return act_fn