squeezellm.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. from aphrodite.common.utils import is_hip
  10. class SqueezeLLMConfig(QuantizationConfig):
  11. """Config class for SqueezeLLM.
  12. Reference: https://arxiv.org/pdf/2306.07629
  13. """
  14. def __init__(
  15. self,
  16. weight_bits: int,
  17. ) -> None:
  18. self.weight_bits = weight_bits
  19. if self.weight_bits != 4:
  20. raise ValueError(
  21. "Currently, only 4-bit weight quantization is supported for "
  22. f"SqueezeLLM, but got {self.weight_bits} bits.")
  23. self.pack_factor = 32 // self.weight_bits
  24. def __repr__(self) -> str:
  25. return f"SqueezeLLMConfig(weight_bits={self.weight_bits})"
  26. def get_name(self) -> str:
  27. return "squeezellm"
  28. def get_supported_act_dtypes(self) -> List[torch.dtype]:
  29. return [torch.half]
  30. def get_min_capability(self) -> int:
  31. return 70
  32. @staticmethod
  33. def get_config_filenames() -> List[str]:
  34. return ["quant_config.json"]
  35. @classmethod
  36. def from_config(cls, config: Dict[str, Any]) -> "SqueezeLLMConfig":
  37. weight_bits = cls.get_from_keys(config, ["wbits"])
  38. return cls(weight_bits)
  39. def get_linear_method(self) -> "SqueezeLLMLinearMethod":
  40. return SqueezeLLMLinearMethod(self)
  41. def get_scaled_act_names(self) -> List[str]:
  42. return []
  43. def merge_weight(self) -> bool:
  44. return True
  45. def quant_vocab(self) -> List[bool]:
  46. return [False, False]
  47. def support_fused_moe(self) -> bool:
  48. return False
  49. class SqueezeLLMLinearMethod(LinearMethodBase):
  50. """Linear method for SqueezeLLM.
  51. Args:
  52. quant_config: The SqueezeLLM quantization config.
  53. """
  54. def __init__(self, quant_config: SqueezeLLMConfig):
  55. self.quant_config = quant_config
  56. def create_weights(self, input_size_per_partition: int,
  57. output_partition_sizes: List[int], input_size: int,
  58. output_size: int,
  59. params_dtype: torch.dtype) -> Dict[str, Any]:
  60. if input_size_per_partition % self.quant_config.pack_factor != 0:
  61. raise ValueError(
  62. "The input size is not aligned with the quantized "
  63. "weight shape. This can be caused by too large "
  64. "tensor parallel size.")
  65. output_size_per_partition = sum(output_partition_sizes)
  66. qweight = Parameter(
  67. torch.empty(
  68. input_size_per_partition // self.quant_config.pack_factor,
  69. output_size_per_partition,
  70. dtype=torch.int32,
  71. ),
  72. requires_grad=False,
  73. )
  74. set_weight_attrs(
  75. qweight, {
  76. "input_dim": 0,
  77. "output_dim": 1,
  78. "packed_dim": 0,
  79. "pack_factor": self.quant_config.pack_factor,
  80. })
  81. lookup_table = Parameter(
  82. torch.empty(
  83. output_size,
  84. self.quant_config.weight_bits**2,
  85. dtype=params_dtype,
  86. ),
  87. requires_grad=False,
  88. )
  89. set_weight_attrs(lookup_table, {
  90. "output_dim": 0,
  91. })
  92. return {
  93. "qweight": qweight,
  94. "lookup_table": lookup_table,
  95. }
  96. def apply_weights(self,
  97. weights: Dict[str, Any],
  98. x: torch.Tensor,
  99. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  100. qweight = weights["qweight"]
  101. lookup_table = weights["lookup_table"]
  102. out_shape = x.shape[:-1] + (qweight.shape[-1], )
  103. reshaped_x = x.reshape(-1, x.shape[-1])
  104. if is_hip():
  105. out_f = torch.zeros(out_shape, dtype=torch.float)
  106. ops.squeezellm_gemm(reshaped_x, qweight, out_f, lookup_table)
  107. out = out_f.to(dtype=torch.float16)
  108. else:
  109. # NOTE: The output tensor should be zero-initialized.
  110. out = torch.zeros(out_shape, dtype=torch.float16)
  111. ops.squeezellm_gemm(reshaped_x, qweight, out, lookup_table)
  112. if bias is not None:
  113. out = out + bias
  114. return out.reshape(out_shape)
  115. def apply_moe_weights(self, w1: Dict[str,
  116. torch.Tensor], w2: Dict[str,
  117. torch.Tensor],
  118. x: torch.Tensor, gating_output: torch.Tensor,
  119. topk: int, renormalize: bool) -> torch.Tensor:
  120. raise NotImplementedError