quantizer_bitnet.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. from typing import TYPE_CHECKING
  15. from .base import HfQuantizer
  16. if TYPE_CHECKING:
  17. from ..modeling_utils import PreTrainedModel
  18. from ..utils.quantization_config import BitNetQuantConfig
  19. from ..utils import is_accelerate_available, is_torch_available, logging
  20. if is_torch_available():
  21. import torch
  22. logger = logging.get_logger(__name__)
  23. class BitNetHfQuantizer(HfQuantizer):
  24. """
  25. 1.58-bit quantization from BitNet quantization method:
  26. Before loading: it converts the linear layers into BitLinear layers during loading.
  27. Check out the paper introducing this method: https://huggingface.co/papers/2402.17764
  28. """
  29. requires_calibration = True
  30. quantization_config: "BitNetQuantConfig"
  31. def __init__(self, quantization_config, **kwargs):
  32. super().__init__(quantization_config, **kwargs)
  33. def validate_environment(self, *args, **kwargs):
  34. if not is_accelerate_available():
  35. raise ImportError("Loading a BitNet quantized model requires accelerate (`pip install accelerate`)")
  36. if not torch.cuda.is_available():
  37. logger.warning_once(
  38. "You don't have a GPU available to load the model, the inference will be slow because of weight unpacking"
  39. )
  40. return
  41. device_map = kwargs.get("device_map")
  42. if device_map is None:
  43. logger.warning_once(
  44. "You have loaded a BitNet model on CPU and have a CUDA device available, make sure to set "
  45. "your model on a GPU device in order to run your model."
  46. )
  47. elif isinstance(device_map, dict):
  48. if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values():
  49. raise ValueError(
  50. "You are attempting to load a BitNet model with a device_map that contains a CPU or disk device."
  51. "This is not supported. Please remove the CPU or disk device from the device_map."
  52. )
  53. def _process_model_before_weight_loading(
  54. self,
  55. model: "PreTrainedModel",
  56. **kwargs,
  57. ):
  58. from ..integrations import replace_with_bitnet_linear
  59. self.modules_to_not_convert = self.get_modules_to_not_convert(
  60. model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
  61. )
  62. model = replace_with_bitnet_linear(
  63. model,
  64. modules_to_not_convert=self.modules_to_not_convert,
  65. quantization_config=self.quantization_config,
  66. )
  67. def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]:
  68. max_memory = {key: val * 0.90 for key, val in max_memory.items()}
  69. return max_memory
  70. def is_serializable(self):
  71. return True
  72. @property
  73. def is_trainable(self) -> bool:
  74. return (
  75. self.quantization_config.linear_class == "autobitlinear"
  76. and self.quantization_config.quantization_mode == "online"
  77. )
  78. @property
  79. def is_qat_trainable(self) -> bool:
  80. """Flag indicating whether the quantized model can carry out quantization aware training"""
  81. return (
  82. self.quantization_config.linear_class == "autobitlinear"
  83. and self.quantization_config.quantization_mode == "online"
  84. )
  85. def get_weight_conversions(self):
  86. from ..core_model_loading import WeightConverter
  87. from ..integrations.bitnet import BitNetDeserialize
  88. if (
  89. self.quantization_config.linear_class == "autobitlinear"
  90. and self.quantization_config.quantization_mode == "offline"
  91. ):
  92. return [
  93. WeightConverter(
  94. source_patterns=["weight"],
  95. target_patterns=["weight"],
  96. operations=[BitNetDeserialize(self)],
  97. )
  98. ]
  99. return []