quantizer_bnb_8bit.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import importlib
  15. from typing import TYPE_CHECKING, Optional, Union
  16. from packaging import version
  17. from .base import HfQuantizer
  18. if TYPE_CHECKING:
  19. from ..modeling_utils import PreTrainedModel
  20. from ..utils import (
  21. ACCELERATE_MIN_VERSION,
  22. is_accelerate_available,
  23. is_bitsandbytes_available,
  24. is_torch_available,
  25. is_torch_xpu_available,
  26. logging,
  27. )
  28. from .quantizers_utils import get_module_from_name
  29. if is_torch_available():
  30. import torch
  31. from ..pytorch_utils import Conv1D
  32. logger = logging.get_logger(__name__)
  33. class Bnb8BitHfQuantizer(HfQuantizer):
  34. """
  35. 8-bit quantization from bitsandbytes quantization method:
  36. before loading: converts transformer layers into Linear8bitLt during loading: load 16bit weight and pass to the
  37. layer object after: quantizes individual weights in Linear8bitLt into 8bit at fitst .cuda() call
  38. saving:
  39. from state dict, as usual; saves weights and 'SCB' component
  40. loading:
  41. need to locate SCB component and pass to the Linear8bitLt object
  42. """
  43. use_keep_in_fp32_modules = True
  44. requires_parameters_quantization = True
  45. requires_calibration = False
  46. required_packages = ["bitsandbytes", "accelerate"]
  47. def __init__(self, quantization_config, **kwargs):
  48. super().__init__(quantization_config, **kwargs)
  49. if self.quantization_config.llm_int8_skip_modules is not None:
  50. self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
  51. def validate_environment(self, *args, **kwargs):
  52. if not is_accelerate_available():
  53. raise ImportError(
  54. f"Using `bitsandbytes` 8-bit quantization requires Accelerate: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
  55. )
  56. if not is_bitsandbytes_available(check_library_only=True):
  57. raise ImportError(
  58. "Using `bitsandbytes` 8-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
  59. )
  60. if not is_torch_available():
  61. raise ImportError(
  62. "The bitsandbytes library requires PyTorch but it was not found in your environment. "
  63. "You can install it with `pip install torch`."
  64. )
  65. # `bitsandbytes` versions older than 0.43.1 eagerly require CUDA at import time,
  66. # so those versions of the library are practically only available when CUDA is too.
  67. if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.1"):
  68. if not torch.cuda.is_available():
  69. raise ImportError(
  70. "The installed version of bitsandbytes (<0.43.1) requires CUDA, but CUDA is not available. "
  71. "You may need to install PyTorch with CUDA support or upgrade bitsandbytes to >=0.43.1."
  72. )
  73. from ..integrations import validate_bnb_backend_availability
  74. from ..utils import is_bitsandbytes_multi_backend_available
  75. bnb_multibackend_is_enabled = is_bitsandbytes_multi_backend_available()
  76. validate_bnb_backend_availability(raise_exception=True)
  77. if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
  78. raise ValueError(
  79. "Converting into 4-bit or 8-bit weights from tf/flax weights is currently not supported, please make"
  80. " sure the weights are in PyTorch format."
  81. )
  82. device_map = kwargs.get("device_map")
  83. if (
  84. device_map is not None
  85. and isinstance(device_map, dict)
  86. and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
  87. ):
  88. device_map_without_lm_head = {
  89. key: device_map[key] for key in device_map if key not in self.modules_to_not_convert
  90. }
  91. if set(device_map.values()) == {"cpu"} and bnb_multibackend_is_enabled:
  92. pass
  93. elif "cpu" in device_map_without_lm_head.values() or "disk" in device_map_without_lm_head.values():
  94. raise ValueError(
  95. "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
  96. "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
  97. "in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to "
  98. "`from_pretrained`. Check "
  99. "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
  100. "for more details. "
  101. )
  102. if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.2"):
  103. raise ValueError(
  104. "You have a version of `bitsandbytes` that is not compatible with 8bit inference and training"
  105. " make sure you have the latest version of `bitsandbytes` installed"
  106. )
  107. def adjust_max_memory(self, max_memory: dict[str, Union[int, str]]) -> dict[str, Union[int, str]]:
  108. # need more space for buffers that are created during quantization
  109. max_memory = {key: val * 0.90 for key, val in max_memory.items()}
  110. return max_memory
  111. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  112. if dtype is None:
  113. # We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
  114. logger.info(
  115. "Overriding dtype=%s with `dtype=torch.float16` due to "
  116. "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
  117. "Pass your own dtype to specify the dtype of the remaining non-linear layers or pass"
  118. " dtype=torch.float16 to remove this warning.",
  119. dtype,
  120. )
  121. dtype = torch.float16
  122. return dtype
  123. def update_device_map(self, device_map):
  124. if device_map is None:
  125. if torch.cuda.is_available():
  126. device_map = {"": torch.cuda.current_device()}
  127. elif is_torch_xpu_available():
  128. device_map = {"": torch.xpu.current_device()}
  129. else:
  130. device_map = {"": "cpu"}
  131. logger.info(
  132. "The device_map was not initialized. "
  133. f"Setting device_map to {device_map}. "
  134. "If you want to use the model for inference, please set device_map ='auto' "
  135. )
  136. return device_map
  137. def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
  138. if target_dtype != torch.int8:
  139. logger.info("target_dtype {target_dtype} is replaced by `torch.int8` for 8-bit BnB quantization")
  140. return torch.int8
  141. def update_unexpected_keys(self, model, unexpected_keys: list[str]) -> list[str]:
  142. bnb_keys = ["SCB", "weight_format"]
  143. return [k for k in unexpected_keys if not any(k.endswith(x) for x in bnb_keys)]
  144. def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
  145. import bitsandbytes as bnb
  146. module, name = get_module_from_name(model, param_name)
  147. return isinstance(module, bnb.nn.Linear8bitLt) and name != "bias"
  148. def create_quantized_param(
  149. self,
  150. model: "PreTrainedModel",
  151. param_value: "torch.Tensor",
  152. param_name: str,
  153. target_device: "torch.device",
  154. **kwargs,
  155. ):
  156. import bitsandbytes as bnb
  157. module, tensor_name = get_module_from_name(model, param_name)
  158. if self.pre_quantized and not self.is_serializable():
  159. raise ValueError(
  160. "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
  161. "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
  162. )
  163. # Those 2 can only happen when self.pre_quantized == True
  164. if tensor_name == "SCB":
  165. setattr(module.weight, "SCB", param_value.to(target_device))
  166. return
  167. # It's not used, but it's getting serialized for BC reason...
  168. elif tensor_name == "weight_format":
  169. return
  170. # Support models using `Conv1D` in place of `nn.Linear` (e.g. openai-community/gpt2) by transposing the weight matrix prior to quantization.
  171. # Since weights are saved in the correct "orientation", we skip transposing when loading.
  172. if issubclass(module.source_cls, Conv1D) and not self.pre_quantized:
  173. param_value = param_value.T
  174. old_value = getattr(module, tensor_name)
  175. kwargs = old_value.__dict__
  176. kwargs.pop("_is_hf_initialized", None)
  177. # Need to pop SCB and reset it because of bnb internals that modifies its value when switching devices ...
  178. SCB = kwargs.pop("SCB", None)
  179. new_value = bnb.nn.Int8Params(param_value.to("cpu"), requires_grad=False, **kwargs).to(target_device)
  180. if SCB is not None:
  181. setattr(new_value, "SCB", SCB)
  182. # Set it to the module
  183. module._parameters[tensor_name] = new_value
  184. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  185. model.is_loaded_in_8bit = True
  186. model.is_8bit_serializable = self.is_serializable()
  187. return model
  188. def _process_model_before_weight_loading(
  189. self,
  190. model: "PreTrainedModel",
  191. device_map,
  192. keep_in_fp32_modules: Optional[list[str]] = None,
  193. **kwargs,
  194. ):
  195. from ..integrations import replace_with_bnb_linear
  196. llm_int8_enable_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
  197. self.modules_to_not_convert = self.get_modules_to_not_convert(
  198. model, self.quantization_config.llm_int8_skip_modules, keep_in_fp32_modules
  199. )
  200. # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
  201. if isinstance(device_map, dict) and len(device_map.keys()) > 1:
  202. keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
  203. if len(keys_on_cpu) > 0 and not llm_int8_enable_fp32_cpu_offload:
  204. raise ValueError(
  205. "If you want to offload some keys to `cpu` or `disk`, you need to set "
  206. "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
  207. " converted to 8-bit but kept in 32-bit."
  208. )
  209. self.modules_to_not_convert.extend(keys_on_cpu)
  210. model = replace_with_bnb_linear(
  211. model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
  212. )
  213. model.config.quantization_config = self.quantization_config
  214. def is_serializable(self, safe_serialization=None):
  215. _bnb_supports_8bit_serialization = version.parse(importlib.metadata.version("bitsandbytes")) > version.parse(
  216. "0.37.2"
  217. )
  218. if not _bnb_supports_8bit_serialization:
  219. logger.warning(
  220. "You are calling `save_pretrained` to a 8-bit converted model, but your `bitsandbytes` version doesn't support it. "
  221. "If you want to save 8-bit models, make sure to have `bitsandbytes>0.37.2` installed. You will most likely face errors or"
  222. " unexpected behaviours."
  223. )
  224. return False
  225. return True
  226. @property
  227. def is_trainable(self) -> bool:
  228. return version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse("0.37.0")
  229. def _dequantize(self, model):
  230. from ..integrations import dequantize_and_replace
  231. model = dequantize_and_replace(
  232. model, self.modules_to_not_convert, quantization_config=self.quantization_config
  233. )
  234. return model