marlin.py 7.3 KB

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