squeezellm.py 4.3 KB

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