bitsandbytes.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. from typing import Any, Dict, List, Optional
  2. import torch
  3. from torch.nn.parameter import Parameter
  4. from aphrodite.modeling.layers.linear import (LinearBase, LinearMethodBase,
  5. set_weight_attrs)
  6. from aphrodite.quantization.base_config import QuantizationConfig
  7. class BitsAndBytesConfig(QuantizationConfig):
  8. """Config class for BitsAndBytes Quantization.
  9. Reference: https://arxiv.org/abs/2305.14314
  10. """
  11. def __init__(
  12. self,
  13. adapter_name_or_path: str,
  14. target_modules: List[str],
  15. ) -> None:
  16. self.adapter_name_or_path = adapter_name_or_path
  17. self.target_modules = target_modules
  18. def __repr__(self) -> str:
  19. return (
  20. f"BitsAndBytesConfig(adapter_name_or_path={self.adapter_name_or_path}"
  21. )
  22. @classmethod
  23. def get_name(self) -> str:
  24. return "bitsandbytes"
  25. @classmethod
  26. def get_supported_act_dtypes(self) -> List[torch.dtype]:
  27. return [torch.float32, torch.float16, torch.bfloat16]
  28. @classmethod
  29. def get_min_capability(self) -> int:
  30. return 70
  31. @staticmethod
  32. def get_config_filenames() -> List[str]:
  33. return [
  34. "adapter_config.json",
  35. ]
  36. @classmethod
  37. def from_config(cls, config: Dict[str, Any]) -> "BitsAndBytesConfig":
  38. adapter_name = cls.get_from_keys(config, ["adapter_name_or_path"])
  39. default_target_modules = [
  40. "gate_proj", "down_proj", "up_proj", "q_proj", "k_proj", "v_proj",
  41. "o_proj"
  42. ]
  43. if adapter_name == "":
  44. target_modules = default_target_modules
  45. else:
  46. target_modules = cls.get_from_keys(config, ["target_modules"])
  47. return cls(adapter_name, target_modules)
  48. def get_quant_method(
  49. self,
  50. layer: torch.nn.Module) -> Optional["BitsAndBytesLinearMethod"]:
  51. if isinstance(layer, LinearBase):
  52. return BitsAndBytesLinearMethod(self)
  53. return None
  54. def get_scaled_act_names(self) -> List[str]:
  55. return ["gelu", "gelu_fast", "gelu_new", "gelu_pytorch_tanh"]
  56. class BitsAndBytesLinearMethod(LinearMethodBase):
  57. """Linear method for BitsAndBytes.
  58. Args:
  59. quant_config: The BitsAndBytes quantization config.
  60. """
  61. def __init__(self, quant_config: BitsAndBytesConfig):
  62. try:
  63. import bitsandbytes
  64. if bitsandbytes.__version__ < "0.42.0":
  65. raise ImportError("bitsandbytes version is wrong. Please "
  66. "install bitsandbytes>=0.42.0.")
  67. except ImportError as err:
  68. raise ImportError("Please install bitsandbytes>=0.42.0 via "
  69. "`pip install bitsandbytes>=0.42.0` to use "
  70. "bitsandbytes quantizer.") from err
  71. self.quant_config = quant_config
  72. def create_weights(self, layer: torch.nn.Module,
  73. input_size_per_partition: int,
  74. output_partition_sizes: List[int], input_size: int,
  75. output_size: int, params_dtype: torch.dtype,
  76. **extra_weight_attrs):
  77. quant_ratio = 0
  78. if params_dtype.is_floating_point:
  79. quant_ratio = torch.finfo(params_dtype).bits // torch.iinfo(
  80. torch.uint8).bits
  81. else:
  82. quant_ratio = torch.iinfo(params_dtype).bits // torch.iinfo(
  83. torch.uint8).bits
  84. if input_size_per_partition * sum(
  85. output_partition_sizes) % quant_ratio != 0:
  86. raise ValueError(
  87. "The input size is not aligned with the quantized "
  88. "weight shape. ")
  89. qweight = Parameter(
  90. torch.empty(
  91. input_size_per_partition * sum(output_partition_sizes) //
  92. quant_ratio,
  93. 1,
  94. dtype=torch.uint8,
  95. ),
  96. requires_grad=False,
  97. )
  98. set_weight_attrs(
  99. qweight,
  100. {
  101. "input_dim": 0,
  102. # In bitsandbytes, a tensor of shape [n,m] is quantized to
  103. #[n*m/pack_ratio, 1],so the output_dim is 0
  104. "output_dim": 0,
  105. "pack_factor": quant_ratio,
  106. "use_bitsandbytes": True,
  107. })
  108. layer.register_parameter("qweight", qweight)
  109. set_weight_attrs(qweight, extra_weight_attrs)
  110. def apply(self,
  111. layer: torch.nn.Module,
  112. x: torch.Tensor,
  113. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  114. # only load the bitsandbytes module when needed
  115. from bitsandbytes import matmul_4bit
  116. original_type = x.dtype
  117. bf_x = x.to(torch.bfloat16)
  118. qweight = layer.qweight
  119. quant_states = qweight.bnb_quant_state
  120. offsets = qweight.bnb_shard_offsets
  121. out_dim_0 = x.shape[0]
  122. out_dim_1 = sum(
  123. [quant_state[1].shape[0] for quant_state in quant_states.items()])
  124. out = torch.empty(out_dim_0,
  125. out_dim_1,
  126. dtype=torch.bfloat16,
  127. device=x.device)
  128. current_index = 0
  129. for i in range(len(quant_states)):
  130. output_size = quant_states[i].shape[0]
  131. # It is more efficient to use out kwarg like
  132. # matmul_4bit(..., out = ...). Infeasible now due to the bug
  133. # https://github.com/TimDettmers/bitsandbytes/issues/1235.
  134. # Need to change after the bug is fixed.
  135. out[:, current_index:current_index + output_size] = matmul_4bit(
  136. bf_x, qweight[offsets[i]:offsets[i + 1]].t(), quant_states[i])
  137. current_index += output_size
  138. out = out.to(original_type)
  139. if bias is not None:
  140. out += bias
  141. return out