quantizer_bnb_8bit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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, Any, Dict, List, 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():
  57. raise ImportError(
  58. "Using `bitsandbytes` 8-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
  59. )
  60. from ..integrations import validate_bnb_backend_availability
  61. from ..utils import is_bitsandbytes_multi_backend_available
  62. bnb_multibackend_is_enabled = is_bitsandbytes_multi_backend_available()
  63. validate_bnb_backend_availability(raise_exception=True)
  64. if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
  65. raise ValueError(
  66. "Converting into 4-bit or 8-bit weights from tf/flax weights is currently not supported, please make"
  67. " sure the weights are in PyTorch format."
  68. )
  69. device_map = kwargs.get("device_map", None)
  70. if (
  71. device_map is not None
  72. and isinstance(device_map, dict)
  73. and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
  74. ):
  75. device_map_without_lm_head = {
  76. key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert
  77. }
  78. if set(device_map.values()) == {"cpu"} and bnb_multibackend_is_enabled:
  79. pass
  80. elif "cpu" in device_map_without_lm_head.values() or "disk" in device_map_without_lm_head.values():
  81. raise ValueError(
  82. "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
  83. "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
  84. "in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to "
  85. "`from_pretrained`. Check "
  86. "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
  87. "for more details. "
  88. )
  89. if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.2"):
  90. raise ValueError(
  91. "You have a version of `bitsandbytes` that is not compatible with 8bit inference and training"
  92. " make sure you have the latest version of `bitsandbytes` installed"
  93. )
  94. def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
  95. # need more space for buffers that are created during quantization
  96. max_memory = {key: val * 0.90 for key, val in max_memory.items()}
  97. return max_memory
  98. def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
  99. if torch_dtype is None:
  100. # We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
  101. logger.info(
  102. "Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
  103. "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
  104. "Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
  105. " torch_dtype=torch.float16 to remove this warning.",
  106. torch_dtype,
  107. )
  108. torch_dtype = torch.float16
  109. return torch_dtype
  110. def update_device_map(self, device_map):
  111. if device_map is None:
  112. if torch.cuda.is_available():
  113. device_map = {"": torch.cuda.current_device()}
  114. elif is_torch_xpu_available():
  115. device_map = {"": f"xpu:{torch.xpu.current_device()}"}
  116. else:
  117. device_map = {"": "cpu"}
  118. logger.info(
  119. "The device_map was not initialized. "
  120. f"Setting device_map to {device_map}. "
  121. "If you want to use the model for inference, please set device_map ='auto' "
  122. )
  123. return device_map
  124. def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
  125. if target_dtype != torch.int8:
  126. logger.info("target_dtype {target_dtype} is replaced by `torch.int8` for 8-bit BnB quantization")
  127. return torch.int8
  128. def check_quantized_param(
  129. self,
  130. model: "PreTrainedModel",
  131. param_value: "torch.Tensor",
  132. param_name: str,
  133. state_dict: Dict[str, Any],
  134. **kwargs,
  135. ):
  136. import bitsandbytes as bnb
  137. module, tensor_name = get_module_from_name(model, param_name)
  138. if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Int8Params):
  139. if self.pre_quantized:
  140. if param_name.replace("weight", "SCB") not in state_dict.keys():
  141. raise ValueError("Missing quantization component `SCB`")
  142. if param_value.dtype != torch.int8:
  143. raise ValueError(
  144. f"Incompatible dtype `{param_value.dtype}` when loading 8-bit prequantized weight. Expected `torch.int8`."
  145. )
  146. return True
  147. return False
  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. state_dict: Dict[str, Any],
  155. unexpected_keys: Optional[List[str]] = None,
  156. ):
  157. """
  158. combines logic from _load_state_dict_into_meta_model and .integrations.bitsandbytes.py::set_module_quantized_tensor_to_device()
  159. needs aux items from state dicts, if found - removes them from unexpected_keys
  160. """
  161. import bitsandbytes as bnb
  162. fp16_statistics_key = param_name.replace("weight", "SCB")
  163. fp16_weights_format_key = param_name.replace("weight", "weight_format")
  164. fp16_statistics = state_dict.get(fp16_statistics_key, None)
  165. fp16_weights_format = state_dict.get(fp16_weights_format_key, None)
  166. module, tensor_name = get_module_from_name(model, param_name)
  167. if tensor_name not in module._parameters:
  168. raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
  169. old_value = getattr(module, tensor_name)
  170. if not isinstance(module._parameters[tensor_name], bnb.nn.Int8Params):
  171. raise ValueError(f"Parameter `{tensor_name}` should only be a `bnb.nn.Int8Params` instance.")
  172. if (
  173. old_value.device == torch.device("meta")
  174. and target_device not in ["meta", torch.device("meta")]
  175. and param_value is None
  176. ):
  177. raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.")
  178. new_value = param_value.to("cpu")
  179. if self.pre_quantized and not self.is_serializable():
  180. raise ValueError(
  181. "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
  182. "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
  183. )
  184. # Support models using `Conv1D` in place of `nn.Linear` (e.g. openai-community/gpt2) by transposing the weight matrix prior to quantization.
  185. # Since weights are saved in the correct "orientation", we skip transposing when loading.
  186. if issubclass(module.source_cls, Conv1D):
  187. if fp16_statistics is None:
  188. new_value = new_value.T
  189. kwargs = old_value.__dict__
  190. new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(target_device)
  191. module._parameters[tensor_name] = new_value
  192. if fp16_statistics is not None:
  193. setattr(module.weight, "SCB", fp16_statistics.to(target_device))
  194. if unexpected_keys is not None:
  195. unexpected_keys.remove(fp16_statistics_key)
  196. # We just need to pop the `weight_format` keys from the state dict to remove unneeded
  197. # messages. The correct format is correctly retrieved during the first forward pass.
  198. if fp16_weights_format is not None and unexpected_keys is not None:
  199. unexpected_keys.remove(fp16_weights_format_key)
  200. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  201. model.is_loaded_in_8bit = True
  202. model.is_8bit_serializable = self.is_serializable()
  203. return model
  204. def _process_model_before_weight_loading(
  205. self,
  206. model: "PreTrainedModel",
  207. device_map,
  208. keep_in_fp32_modules: List[str] = [],
  209. **kwargs,
  210. ):
  211. from ..integrations import get_keys_to_not_convert, replace_with_bnb_linear
  212. llm_int8_enable_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
  213. # We keep some modules such as the lm_head in their original dtype for numerical stability reasons
  214. if self.quantization_config.llm_int8_skip_modules is None:
  215. self.modules_to_not_convert = get_keys_to_not_convert(model)
  216. else:
  217. self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
  218. if not isinstance(self.modules_to_not_convert, list):
  219. self.modules_to_not_convert = [self.modules_to_not_convert]
  220. self.modules_to_not_convert.extend(keep_in_fp32_modules)
  221. # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
  222. if isinstance(device_map, dict) and len(device_map.keys()) > 1:
  223. keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
  224. if len(keys_on_cpu) > 0 and not llm_int8_enable_fp32_cpu_offload:
  225. raise ValueError(
  226. "If you want to offload some keys to `cpu` or `disk`, you need to set "
  227. "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
  228. " converted to 8-bit but kept in 32-bit."
  229. )
  230. self.modules_to_not_convert.extend(keys_on_cpu)
  231. model = replace_with_bnb_linear(
  232. model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
  233. )
  234. # TODO: consider bringing replace_with_bnb_linear() code from ..integrations/bitsandbyter.py to here
  235. model.config.quantization_config = self.quantization_config
  236. def is_serializable(self, safe_serialization=None):
  237. _bnb_supports_8bit_serialization = version.parse(importlib.metadata.version("bitsandbytes")) > version.parse(
  238. "0.37.2"
  239. )
  240. if not _bnb_supports_8bit_serialization:
  241. logger.warning(
  242. "You are calling `save_pretrained` to a 8-bit converted model, but your `bitsandbytes` version doesn't support it. "
  243. "If you want to save 8-bit models, make sure to have `bitsandbytes>0.37.2` installed. You will most likely face errors or"
  244. " unexpected behaviours."
  245. )
  246. return False
  247. return True
  248. @property
  249. def is_trainable(self) -> bool:
  250. return version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse("0.37.0")
  251. def _dequantize(self, model):
  252. from ..integrations import dequantize_and_replace
  253. model = dequantize_and_replace(
  254. model, self.modules_to_not_convert, quantization_config=self.quantization_config
  255. )
  256. return model