squeezellm.py 4.3 KB

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