activation.py 5.5 KB

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