squeezellm.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 rope_style(self) -> Optional[bool]:
  46. return None
  47. class SqueezeLLMLinearMethod(LinearMethodBase):
  48. """Linear method for SqueezeLLM.
  49. Args:
  50. quant_config: The SqueezeLLM quantization config.
  51. """
  52. def __init__(self, quant_config: SqueezeLLMConfig):
  53. self.quant_config = quant_config
  54. def create_weights(
  55. self,
  56. input_size_per_partition: int,
  57. output_partition_sizes: List[int],
  58. input_size: int,
  59. output_size: int,
  60. params_dtype: torch.dtype,
  61. ) -> Dict[str, Any]:
  62. if input_size_per_partition % self.quant_config.pack_factor != 0:
  63. raise ValueError(
  64. "The input size is not aligned with the quantized "
  65. "weight shape. This can be caused by too large "
  66. "tensor parallel size.")
  67. output_size_per_partition = sum(output_partition_sizes)
  68. qweight = Parameter(
  69. torch.empty(
  70. input_size_per_partition // self.quant_config.pack_factor,
  71. output_size_per_partition,
  72. dtype=torch.int32,
  73. ),
  74. requires_grad=False,
  75. )
  76. set_weight_attrs(
  77. qweight, {
  78. "input_dim": 0,
  79. "output_dim": 1,
  80. "packed_dim": 0,
  81. "pack_factor": self.quant_config.pack_factor,
  82. })
  83. lookup_table = Parameter(
  84. torch.empty(
  85. output_size,
  86. self.quant_config.weight_bits**2,
  87. dtype=params_dtype,
  88. ),
  89. requires_grad=False,
  90. )
  91. set_weight_attrs(lookup_table, {
  92. "output_dim": 0,
  93. })
  94. return {
  95. "qweight": qweight,
  96. "lookup_table": lookup_table,
  97. }
  98. def apply_weights(self,
  99. weights: Dict[str, Any],
  100. x: torch.Tensor,
  101. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  102. qweight = weights["qweight"]
  103. lookup_table = weights["lookup_table"]
  104. out_shape = x.shape[:-1] + (qweight.shape[-1], )
  105. reshaped_x = x.reshape(-1, x.shape[-1])
  106. if is_hip():
  107. out_f = torch.zeros(out_shape, dtype=torch.float)
  108. ops.squeezellm_gemm(reshaped_x, qweight, out_f, lookup_table)
  109. out = out_f.to(dtype=torch.float16)
  110. else:
  111. # NOTE: The output tensor should be zero-initialized.
  112. out = torch.zeros(out_shape, dtype=torch.float16)
  113. ops.squeezellm_gemm(reshaped_x, qweight, out, lookup_table)
  114. if bias is not None:
  115. out = out + bias
  116. return out.reshape(out_shape)