gptq_marlin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. from typing import Any, Dict, List, Optional, Set
  2. import torch
  3. from loguru import logger
  4. from aphrodite.common.utils import is_hip
  5. from aphrodite.modeling.layers.linear import LinearBase, LinearMethodBase
  6. from aphrodite.modeling.layers.vocab_parallel_embedding import ParallelLMHead
  7. from aphrodite.modeling.parameter import (ChannelQuantScaleParameter,
  8. GroupQuantScaleParameter,
  9. PackedAphroditeParameter,
  10. PackedColumnParameter,
  11. RowAphroditeParameter)
  12. from aphrodite.quantization.base_config import QuantizationConfig
  13. from aphrodite.quantization.kernels import (MPLinearLayerConfig,
  14. choose_mp_linear_kernel)
  15. from aphrodite.quantization.utils.marlin_utils import (
  16. check_marlin_supported, marlin_repeat_scales_on_all_ranks,
  17. verify_marlin_supported)
  18. from aphrodite.scalar_type import scalar_types
  19. class GPTQMarlinConfig(QuantizationConfig):
  20. """Config class for GPTQ Marlin"""
  21. # (num_bits, is_sym) -> quant_type
  22. TYPE_MAP = {
  23. (4, True): scalar_types.uint4b8,
  24. (8, True): scalar_types.uint8b128,
  25. }
  26. def __init__(self, weight_bits: int, group_size: int, desc_act: bool,
  27. is_sym: bool, lm_head_quantized: bool) -> None:
  28. if desc_act and group_size == -1:
  29. # In this case, act_order == True is the same as act_order == False
  30. # (since we have only one group per output channel)
  31. desc_act = False
  32. self.pack_factor = 32 // weight_bits # packed into int32
  33. self.group_size = group_size
  34. self.desc_act = desc_act
  35. self.lm_head_quantized = lm_head_quantized
  36. if (weight_bits, is_sym) not in self.TYPE_MAP:
  37. raise ValueError("Unsupported quantization config: "
  38. f"bits={weight_bits}, sym={is_sym}")
  39. self.quant_type = self.TYPE_MAP[(weight_bits, is_sym)]
  40. def __repr__(self) -> str:
  41. return (f"GPTQMarlinConfig(quant_type={self.quant_type}, "
  42. f"group_size={self.group_size}, "
  43. f"desc_act={self.desc_act}, "
  44. f"lm_head_quantized={self.lm_head_quantized})")
  45. @classmethod
  46. def get_name(cls) -> str:
  47. return "gptq_marlin"
  48. @classmethod
  49. def get_supported_act_dtypes(cls) -> List[torch.dtype]:
  50. return [torch.half, torch.bfloat16]
  51. @classmethod
  52. def get_min_capability(cls) -> int:
  53. return 80
  54. @classmethod
  55. def get_config_filenames(cls) -> List[str]:
  56. return ["quantize_config.json"]
  57. @classmethod
  58. def from_config(cls, config: Dict[str, Any]) -> "GPTQMarlinConfig":
  59. weight_bits = cls.get_from_keys(config, ["bits"])
  60. group_size = cls.get_from_keys(config, ["group_size"])
  61. desc_act = cls.get_from_keys(config, ["desc_act"])
  62. is_sym = cls.get_from_keys(config, ["sym"])
  63. lm_head_quantized = cls.get_from_keys_or(config, ["lm_head"],
  64. default=False)
  65. return cls(weight_bits, group_size, desc_act, is_sym,
  66. lm_head_quantized)
  67. @classmethod
  68. def override_quantization_method(cls, hf_quant_cfg,
  69. user_quant) -> Optional[str]:
  70. can_convert = cls.is_gptq_marlin_compatible(hf_quant_cfg)
  71. is_valid_user_quant = (user_quant is None or user_quant == "marlin"
  72. or user_quant == "gptq_marlin")
  73. if is_hip():
  74. return None
  75. if can_convert and is_valid_user_quant:
  76. msg = ("The model is convertible to {} during runtime."
  77. " Using {} kernel.".format(cls.get_name(), cls.get_name()))
  78. logger.info(msg)
  79. return cls.get_name()
  80. if can_convert and user_quant == "gptq":
  81. logger.info("Detected that the model can run with gptq_marlin"
  82. ", however you specified quantization=gptq explicitly,"
  83. " so forcing gptq. Use quantization=gptq_marlin for"
  84. " faster inference")
  85. return None
  86. def get_quant_method(self, layer: torch.nn.Module,
  87. prefix: str) -> Optional["GPTQMarlinLinearMethod"]:
  88. if (isinstance(layer, LinearBase) or
  89. (isinstance(layer, ParallelLMHead) and self.lm_head_quantized)):
  90. return GPTQMarlinLinearMethod(self)
  91. return None
  92. def get_scaled_act_names(self) -> List[str]:
  93. return []
  94. @classmethod
  95. def is_gptq_marlin_compatible(cls, quant_config: Dict[str, Any]):
  96. # Extract data from quant config.
  97. quant_method = quant_config.get("quant_method", "").lower()
  98. num_bits = quant_config.get("bits", None)
  99. group_size = quant_config.get("group_size", None)
  100. sym = quant_config.get("sym", None)
  101. desc_act = quant_config.get("desc_act", None)
  102. if quant_method != "gptq":
  103. return False
  104. # If we cannot find the info needed in the config, cannot convert.
  105. if (num_bits is None or group_size is None or sym is None
  106. or desc_act is None):
  107. return False
  108. if (num_bits, sym) not in cls.TYPE_MAP:
  109. return False
  110. return check_marlin_supported(quant_type=cls.TYPE_MAP[(num_bits, sym)],
  111. group_size=group_size)
  112. class GPTQMarlinLinearMethod(LinearMethodBase):
  113. """Linear method for GPTQ Marlin.
  114. Args:
  115. quant_config: The GPTQ Marlin quantization config.
  116. """
  117. _kernel_backends_being_used: Set[str] = set()
  118. def __init__(self, quant_config: GPTQMarlinConfig) -> None:
  119. self.quant_config = quant_config
  120. # Verify supported on platform.
  121. verify_marlin_supported(quant_type=self.quant_config.quant_type,
  122. group_size=self.quant_config.group_size)
  123. def create_weights(
  124. self,
  125. layer: torch.nn.Module,
  126. input_size_per_partition: int,
  127. output_partition_sizes: List[int],
  128. input_size: int,
  129. output_size: int,
  130. params_dtype: torch.dtype,
  131. **extra_weight_attrs,
  132. ) -> None:
  133. output_size_per_partition = sum(output_partition_sizes)
  134. is_row_parallel = input_size != input_size_per_partition
  135. weight_loader = extra_weight_attrs.get("weight_loader")
  136. mp_linear_kernel_config = MPLinearLayerConfig(
  137. full_weight_shape=(input_size, output_size),
  138. partition_weight_shape=\
  139. (input_size_per_partition, output_size_per_partition),
  140. weight_type=self.quant_config.quant_type,
  141. act_type=params_dtype,
  142. group_size=self.quant_config.group_size,
  143. zero_points=False,
  144. has_g_idx=self.quant_config.desc_act
  145. )
  146. kernel_type = choose_mp_linear_kernel(mp_linear_kernel_config)
  147. if kernel_type.__name__ not in self._kernel_backends_being_used:
  148. logger.info(
  149. f"Using {kernel_type.__name__} for GPTQMarlinLinearMethod")
  150. self._kernel_backends_being_used.add(kernel_type.__name__)
  151. # Normalize group_size
  152. if self.quant_config.group_size != -1:
  153. group_size = self.quant_config.group_size
  154. else:
  155. group_size = input_size
  156. # Determine sharding
  157. if marlin_repeat_scales_on_all_ranks(self.quant_config.desc_act,
  158. self.quant_config.group_size,
  159. is_row_parallel):
  160. # By setting scale_dim == None, weight_loader will
  161. # repeat the scales on each GPU in TP>1 case.
  162. scales_and_zp_input_dim = None
  163. scales_and_zp_size = input_size // group_size
  164. else:
  165. # By setting scale_dim == 0, weight_loader will
  166. # shard the scales in TP>1 case.
  167. scales_and_zp_input_dim = 0
  168. scales_and_zp_size = input_size_per_partition // group_size
  169. # Quantized weights
  170. qweight = PackedAphroditeParameter(
  171. data=torch.empty(
  172. input_size_per_partition // self.quant_config.pack_factor,
  173. output_size_per_partition,
  174. dtype=torch.int32,
  175. ),
  176. input_dim=0,
  177. output_dim=1,
  178. packed_dim=0,
  179. packed_factor=self.quant_config.pack_factor,
  180. weight_loader=weight_loader)
  181. # Activation order
  182. g_idx = RowAphroditeParameter(data=torch.empty(
  183. input_size_per_partition,
  184. dtype=torch.int32,
  185. ),
  186. input_dim=0,
  187. weight_loader=weight_loader)
  188. qzeros_args = {
  189. "data":
  190. torch.empty(
  191. scales_and_zp_size,
  192. output_size_per_partition // self.quant_config.pack_factor,
  193. dtype=torch.int32,
  194. ),
  195. "weight_loader":
  196. weight_loader
  197. }
  198. weight_scale_args = {
  199. "data":
  200. torch.empty(
  201. scales_and_zp_size,
  202. output_size_per_partition,
  203. dtype=params_dtype,
  204. ),
  205. "weight_loader":
  206. weight_loader
  207. }
  208. if scales_and_zp_input_dim is None:
  209. scales = ChannelQuantScaleParameter(output_dim=1,
  210. **weight_scale_args)
  211. qzeros = PackedColumnParameter(
  212. output_dim=1,
  213. packed_dim=1,
  214. packed_factor=self.quant_config.pack_factor,
  215. **qzeros_args)
  216. else:
  217. scales = GroupQuantScaleParameter(output_dim=1,
  218. input_dim=0,
  219. **weight_scale_args)
  220. qzeros = PackedAphroditeParameter(
  221. input_dim=0,
  222. output_dim=1,
  223. packed_dim=1,
  224. packed_factor=self.quant_config.pack_factor,
  225. **qzeros_args)
  226. layer.register_parameter("qweight", qweight)
  227. layer.register_parameter("g_idx", g_idx)
  228. layer.register_parameter("scales", scales)
  229. layer.register_parameter("qzeros", qzeros)
  230. self.kernel = kernel_type(mp_linear_kernel_config,
  231. w_q_param_name="qweight",
  232. w_s_param_name="scales",
  233. w_zp_param_name="qzeros",
  234. w_gidx_param_name="g_idx")
  235. def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
  236. self.kernel.process_weights_after_loading(layer)
  237. def apply(
  238. self,
  239. layer: torch.nn.Module,
  240. x: torch.Tensor,
  241. bias: Optional[torch.Tensor] = None,
  242. ) -> torch.Tensor:
  243. return self.kernel.apply_weights(layer, x, bias)