squeezellm.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from typing import Any, Dict, List, Optional
  2. import torch
  3. from torch.nn.parameter import Parameter
  4. from aphrodite import _custom_ops as ops
  5. from aphrodite.common.utils import is_hip
  6. from aphrodite.modeling.layers.linear import LinearBase
  7. from aphrodite.modeling.utils import set_weight_attrs
  8. from aphrodite.quantization.base_config import (QuantizationConfig,
  9. QuantizeMethodBase)
  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. @classmethod
  31. def get_min_capability(cls) -> int:
  32. return 70
  33. @staticmethod
  34. def get_config_filenames() -> List[str]:
  35. return ["quant_config.json"]
  36. @classmethod
  37. def from_config(cls, config: Dict[str, Any]) -> "SqueezeLLMConfig":
  38. weight_bits = cls.get_from_keys(config, ["wbits"])
  39. return cls(weight_bits)
  40. def get_quant_method(self, layer: torch.nn.Module,
  41. prefix: str) -> Optional[QuantizeMethodBase]:
  42. if isinstance(layer, LinearBase):
  43. return SqueezeLLMLinearMethod(self)
  44. return
  45. def get_scaled_act_names(self) -> List[str]:
  46. return []
  47. class SqueezeLLMLinearMethod(QuantizeMethodBase):
  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(self, layer: torch.nn.Module,
  55. input_size_per_partition: int,
  56. output_partition_sizes: List[int], input_size: int,
  57. output_size: int, params_dtype: torch.dtype,
  58. **extra_weight_attrs):
  59. if input_size_per_partition % self.quant_config.pack_factor != 0:
  60. raise ValueError(
  61. "The input size is not aligned with the quantized "
  62. "weight shape. This can be caused by too large "
  63. "tensor parallel size.")
  64. output_size_per_partition = sum(output_partition_sizes)
  65. qweight = Parameter(
  66. torch.empty(
  67. input_size_per_partition // self.quant_config.pack_factor,
  68. output_size_per_partition,
  69. dtype=torch.int32,
  70. ),
  71. requires_grad=False,
  72. )
  73. set_weight_attrs(
  74. qweight, {
  75. "input_dim": 0,
  76. "output_dim": 1,
  77. "packed_dim": 0,
  78. "pack_factor": self.quant_config.pack_factor,
  79. })
  80. lookup_table = Parameter(
  81. torch.empty(
  82. output_size,
  83. self.quant_config.weight_bits**2,
  84. dtype=params_dtype,
  85. ),
  86. requires_grad=False,
  87. )
  88. set_weight_attrs(lookup_table, {
  89. "output_dim": 0,
  90. })
  91. layer.register_parameter("qweight", qweight)
  92. set_weight_attrs(qweight, extra_weight_attrs)
  93. layer.register_parameter("lookup_table", lookup_table)
  94. set_weight_attrs(lookup_table, extra_weight_attrs)
  95. def apply(self,
  96. layer: torch.nn.Module,
  97. x: torch.Tensor,
  98. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  99. qweight = layer.qweight
  100. lookup_table = layer.lookup_table
  101. out_shape = x.shape[:-1] + (qweight.shape[-1], )
  102. reshaped_x = x.reshape(-1, x.shape[-1])
  103. if is_hip():
  104. out_f = torch.zeros(out_shape, dtype=torch.float)
  105. ops.squeezellm_gemm(reshaped_x, qweight, out_f, lookup_table)
  106. out = out_f.to(dtype=torch.float16)
  107. else:
  108. # NOTE: The output tensor should be zero-initialized.
  109. out = torch.zeros(out_shape, dtype=torch.float16)
  110. ops.squeezellm_gemm(reshaped_x, qweight, out, lookup_table)
  111. if bias is not None:
  112. out.add_(bias)
  113. return out.reshape(out_shape)