bitsandbytes.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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(cls) -> 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(self, layer: torch.nn.Module,
  49. prefix: str) -> Optional["BitsAndBytesLinearMethod"]:
  50. if isinstance(layer, LinearBase):
  51. return BitsAndBytesLinearMethod(self)
  52. return None
  53. def get_scaled_act_names(self) -> List[str]:
  54. return ["gelu", "gelu_fast", "gelu_new", "gelu_pytorch_tanh"]
  55. class BitsAndBytesLinearMethod(LinearMethodBase):
  56. """Linear method for BitsAndBytes.
  57. Args:
  58. quant_config: The BitsAndBytes quantization config.
  59. """
  60. def __init__(self, quant_config: BitsAndBytesConfig):
  61. try:
  62. import bitsandbytes
  63. if bitsandbytes.__version__ < "0.42.0":
  64. raise ImportError("bitsandbytes version is wrong. Please "
  65. "install bitsandbytes>=0.42.0.")
  66. except ImportError as err:
  67. raise ImportError("Please install bitsandbytes>=0.42.0 via "
  68. "`pip install bitsandbytes>=0.42.0` to use "
  69. "bitsandbytes quantizer.") from err
  70. self.quant_config = quant_config
  71. def create_weights(self, layer: torch.nn.Module,
  72. input_size_per_partition: int,
  73. output_partition_sizes: List[int], input_size: int,
  74. output_size: int, params_dtype: torch.dtype,
  75. **extra_weight_attrs):
  76. quant_ratio = 0
  77. if params_dtype.is_floating_point:
  78. quant_ratio = torch.finfo(params_dtype).bits // torch.iinfo(
  79. torch.uint8).bits
  80. else:
  81. quant_ratio = torch.iinfo(params_dtype).bits // torch.iinfo(
  82. torch.uint8).bits
  83. if input_size_per_partition * sum(
  84. output_partition_sizes) % quant_ratio != 0:
  85. raise ValueError(
  86. "The input size is not aligned with the quantized "
  87. "weight shape. ")
  88. qweight = Parameter(
  89. torch.empty(
  90. input_size_per_partition * sum(output_partition_sizes) //
  91. quant_ratio,
  92. 1,
  93. dtype=torch.uint8,
  94. ),
  95. requires_grad=False,
  96. )
  97. set_weight_attrs(
  98. qweight,
  99. {
  100. "input_dim": 0,
  101. # In bitsandbytes, a tensor of shape [n,m] is quantized to
  102. #[n*m/pack_ratio, 1],so the output_dim is 0
  103. "output_dim": 0,
  104. "pack_factor": quant_ratio,
  105. "use_bitsandbytes": True,
  106. })
  107. layer.register_parameter("qweight", qweight)
  108. set_weight_attrs(qweight, extra_weight_attrs)
  109. def apply(self,
  110. layer: torch.nn.Module,
  111. x: torch.Tensor,
  112. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  113. # only load the bitsandbytes module when needed
  114. from bitsandbytes import matmul_4bit
  115. original_type = x.dtype
  116. bf_x = x.to(torch.bfloat16)
  117. qweight = layer.qweight
  118. quant_states = qweight.bnb_quant_state
  119. offsets = qweight.bnb_shard_offsets
  120. out_dim_0 = x.shape[0]
  121. out_dim_1 = sum(
  122. [quant_state[1].shape[0] for quant_state in quant_states.items()])
  123. out = torch.empty(out_dim_0,
  124. out_dim_1,
  125. dtype=torch.bfloat16,
  126. device=x.device)
  127. current_index = 0
  128. for i in range(len(quant_states)):
  129. output_size = quant_states[i].shape[0]
  130. # It is more efficient to use out kwarg like
  131. # matmul_4bit(..., out = ...). Infeasible now due to the bug
  132. # https://github.com/TimDettmers/bitsandbytes/issues/1235.
  133. # Need to change after the bug is fixed.
  134. out[:, current_index:current_index + output_size] = matmul_4bit(
  135. bf_x, qweight[offsets[i]:offsets[i + 1]].t(), quant_states[i])
  136. current_index += output_size
  137. out = out.to(original_type)
  138. if bias is not None:
  139. out += bias
  140. return out