marlin.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. from typing import Any, Dict, List, Optional
  2. import torch
  3. from torch.nn.parameter import Parameter
  4. from aphrodite._C import ops
  5. from aphrodite.modeling.layers.linear import (LinearMethodBase,
  6. set_weight_attrs)
  7. from aphrodite.modeling.layers.quantization.base_config import (
  8. QuantizationConfig)
  9. class MarlinConfig(QuantizationConfig):
  10. """Config class for Marlin.
  11. Reference: https://github.com/IST-DASLab/marlin/tree/master
  12. """
  13. def __init__(
  14. self,
  15. group_size: int,
  16. ) -> None:
  17. # Group size for the quantization.
  18. self.group_size = group_size
  19. if self.group_size != 128 and self.group_size != -1:
  20. raise ValueError(
  21. "Currently, only group size 128 and -1 (channelwise) "
  22. "is supported for Marlin, but got group_size of "
  23. f"{self.group_size}")
  24. # 4 Bits packed into 32 bit datatype.
  25. self.pack_factor = 32 // 4
  26. # Tile size used by marlin kernels.
  27. self.tile_size = 16
  28. # Min out_features dim
  29. self.min_n_threads = 64
  30. # Min in_features dim
  31. self.min_k_threads = 128
  32. # Max parallel problems to solve at once (improves large
  33. # batch performance)
  34. self.max_parallel = 16
  35. # Permutation length used by the marlin kernels.
  36. self.perm_len = 1024
  37. def __repr__(self) -> str:
  38. return f"MarlinConfig(group_size={self.group_size})"
  39. @classmethod
  40. def get_name(cls) -> str:
  41. return "marlin"
  42. @classmethod
  43. def get_supported_act_dtypes(cls) -> List[torch.dtype]:
  44. return [torch.half]
  45. @classmethod
  46. # Need to figure it out
  47. def get_min_capability(cls) -> int:
  48. return 80
  49. @classmethod
  50. def get_config_filenames(cls) -> List[str]:
  51. return ["quantize_config.json"]
  52. @classmethod
  53. def from_config(cls, config: Dict[str, Any]) -> "MarlinConfig":
  54. group_size = cls.get_from_keys(config, ["group_size"])
  55. return cls(group_size)
  56. def get_linear_method(self) -> "MarlinLinearMethod":
  57. return MarlinLinearMethod(self)
  58. def get_scaled_act_names(self) -> List[str]:
  59. return []
  60. def merge_weight(self) -> bool:
  61. return True
  62. def quant_vocab(self) -> List[bool]:
  63. return [False, False]
  64. def support_fused_moe(self) -> bool:
  65. return False
  66. class MarlinLinearMethod(LinearMethodBase):
  67. """Linear method for Marlin.
  68. Args:
  69. quant_config: The Marlin quantization config.
  70. """
  71. def __init__(self, quant_config: MarlinConfig):
  72. self.quant_config = quant_config
  73. def create_weights(
  74. self,
  75. input_size_per_partition: int,
  76. output_partition_sizes: List[int],
  77. input_size: int,
  78. output_size: int,
  79. params_dtype: torch.dtype,
  80. ) -> Dict[str, Any]:
  81. del output_size # Unused.
  82. if params_dtype != torch.float16:
  83. raise ValueError(
  84. f"The params dtype must be float16, but got {params_dtype}")
  85. output_size_per_partition = sum(output_partition_sizes)
  86. # Validate output_size_per_partition
  87. if output_size_per_partition % self.quant_config.min_n_threads != 0:
  88. raise ValueError(
  89. f"Weight output_size_per_partition = "
  90. f"{output_size_per_partition} is not divisible by "
  91. f"min_n_threads = {self.quant_config.min_n_threads}.")
  92. if output_size_per_partition % self.quant_config.pack_factor != 0:
  93. raise ValueError(
  94. f"Weight output_size_per_partition = "
  95. f"{output_size_per_partition} is not divisible by "
  96. f"pack_factor = {self.quant_config.pack_factor}.")
  97. # Validate input_size_per_partition
  98. if input_size_per_partition % self.quant_config.min_k_threads != 0:
  99. raise ValueError(
  100. f"Weight input_size_per_partition = "
  101. f"{input_size_per_partition} is not divisible by "
  102. f"min_k_threads = {self.quant_config.min_k_threads}.")
  103. if (self.quant_config.group_size != -1 and
  104. input_size_per_partition % self.quant_config.group_size != 0):
  105. raise ValueError(f"Weight input_size_per_partition = "
  106. f"{input_size_per_partition} is not divisible by "
  107. f"group_size = {self.quant_config.group_size}.")
  108. # Check that we have at least 4 tiles horizontally in the shard
  109. num_tiles_per_perm = self.quant_config.perm_len // (
  110. self.quant_config.tile_size**2)
  111. if output_size_per_partition % num_tiles_per_perm != 0:
  112. raise ValueError(
  113. "Each permutation group must reside on the same gpu")
  114. # Quantized 4Bit weights packed into Int32.
  115. qweight = Parameter(
  116. torch.empty(
  117. input_size_per_partition // self.quant_config.tile_size,
  118. output_size_per_partition * self.quant_config.tile_size //
  119. self.quant_config.pack_factor,
  120. device="cuda",
  121. dtype=torch.int32,
  122. ),
  123. requires_grad=False,
  124. )
  125. set_weight_attrs(
  126. qweight,
  127. {
  128. "input_dim": 0,
  129. "output_dim": 1,
  130. "packed_dim": 1,
  131. "pack_factor": self.quant_config.pack_factor,
  132. "marlin_tile_size": self.quant_config.tile_size,
  133. },
  134. )
  135. # Determine if channelwise or not
  136. input_groups = (1 if self.quant_config.group_size == -1 else
  137. input_size_per_partition //
  138. self.quant_config.group_size)
  139. scales = Parameter(
  140. torch.empty(
  141. input_groups,
  142. output_size_per_partition,
  143. device="cuda",
  144. dtype=params_dtype,
  145. ),
  146. requires_grad=False,
  147. )
  148. set_weight_attrs(
  149. scales,
  150. {
  151. "input_dim": None if input_groups == 1 else 0,
  152. "output_dim": 1,
  153. },
  154. )
  155. # Allocate workspace (Used for internal locking mechanism)
  156. max_workspace_size = (
  157. output_size_per_partition //
  158. self.quant_config.min_n_threads) * self.quant_config.max_parallel
  159. workspace = Parameter(torch.zeros(max_workspace_size,
  160. device="cuda",
  161. dtype=torch.int),
  162. requires_grad=False)
  163. return {
  164. "B": qweight,
  165. "s": scales,
  166. "workspace": workspace,
  167. }
  168. def apply_weights(
  169. self,
  170. weights: Dict[str, Any],
  171. x: torch.Tensor,
  172. bias: Optional[torch.Tensor] = None,
  173. ) -> torch.Tensor:
  174. qweight = weights["B"]
  175. scales = weights["s"]
  176. workspace = weights["workspace"]
  177. x_2d = x.view(-1, x.shape[-1])
  178. size_m = x_2d.shape[0]
  179. size_k = x_2d.shape[1]
  180. size_n = scales.shape[1]
  181. output_2d = ops.marlin_gemm(x_2d, qweight, scales, workspace, size_m,
  182. size_n, size_k)
  183. output = output_2d.view(x.shape[:-1] + (output_2d.shape[1], ))
  184. if bias is not None:
  185. output.add_(bias) # In-place add
  186. return output
  187. def apply_moe_weights(self, w1: Dict[str,
  188. torch.Tensor], w2: Dict[str,
  189. torch.Tensor],
  190. x: torch.Tensor, gating_output: torch.Tensor,
  191. topk: int, renormalize: bool) -> torch.Tensor:
  192. raise NotImplementedError