awq.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Copyright 2023 The HuggingFace 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. "AWQ (Activation aware Weight Quantization) integration file"
  15. from ..quantizers.quantizers_utils import should_convert_module
  16. from ..utils import is_torch_available, logging
  17. if is_torch_available():
  18. import torch
  19. import torch.nn as nn
  20. logger = logging.get_logger(__name__)
  21. AWQ_SCALES_MAPPINGS = {
  22. "starcoder2": {"act": "act", "layer_before_act": "c_fc"},
  23. "RefinedWebModel": {"act": "act", "layer_before_act": "dense_h_to_4h"},
  24. "falcon": {"act": "act", "layer_before_act": "dense_h_to_4h"},
  25. "mpt": {"act": "act", "layer_before_act": "up_proj"},
  26. "gptj": {"act": "act", "layer_before_act": "fc_in"},
  27. "gpt_neox": {"act": "act", "layer_before_act": "dense_h_to_4h"},
  28. "gpt_bigcode": {"act": "act", "layer_before_act": "c_fc"},
  29. "bloom": {"act": "gelu_impl", "layer_before_act": "dense_h_to_4h"},
  30. }
  31. def replace_quantization_scales(model, model_type):
  32. from gptqmodel.quantization.awq.modules.act import ScaledActivation
  33. if model_type not in AWQ_SCALES_MAPPINGS:
  34. return model
  35. for name, module in model.named_children():
  36. act_name = AWQ_SCALES_MAPPINGS[model_type]["act"]
  37. layer_before_act_name = AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"]
  38. if name == act_name and hasattr(model, layer_before_act_name):
  39. layer_before_act = getattr(model, AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"])
  40. size = layer_before_act.out_features
  41. scale_like = torch.ones(size)
  42. model._modules[name] = ScaledActivation(module, scale_like)
  43. _ = replace_quantization_scales(module, model_type)
  44. return model
  45. def replace_with_awq_linear(
  46. model,
  47. modules_to_not_convert=None,
  48. quantization_config=None,
  49. device_map: str | dict | None = None,
  50. ) -> bool:
  51. """
  52. Public method that replaces the linear layers of the given model with awq quantized layers.
  53. Args:
  54. model (`torch.nn.Module`):
  55. The model to convert, can be any `torch.nn.Module` instance.
  56. quantization_config (`AwqConfig`):
  57. The quantization config object that contains the quantization parameters.
  58. modules_to_not_convert (`list[str]`, *optional*, defaults to `None`):
  59. A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
  60. converted.
  61. device_map (`Union[str, dict]`, *optional*, defaults to `None`):
  62. The device map that maps the parameters to the device
  63. """
  64. from gptqmodel.quantization import METHOD
  65. from gptqmodel.utils.importer import hf_select_quant_linear_v2
  66. target_cls = hf_select_quant_linear_v2(
  67. bits=quantization_config.bits,
  68. group_size=quantization_config.group_size,
  69. desc_act=False,
  70. sym=False,
  71. format=quantization_config.format,
  72. backend=quantization_config.backend,
  73. device_map=device_map,
  74. quant_method=METHOD.AWQ,
  75. zero_point=quantization_config.zero_point,
  76. pack=False,
  77. )
  78. for module_name, module in model.named_modules():
  79. if not should_convert_module(module_name, modules_to_not_convert):
  80. continue
  81. with torch.device("meta"):
  82. if isinstance(module, nn.Linear):
  83. new_module = target_cls(
  84. bits=quantization_config.bits,
  85. sym=quantization_config.sym,
  86. desc_act=quantization_config.desc_act,
  87. group_size=quantization_config.group_size,
  88. in_features=module.in_features,
  89. out_features=module.out_features,
  90. bias=module.bias is not None,
  91. dev=module.weight.device,
  92. register_buffers=True,
  93. )
  94. new_module.requires_grad_(False)
  95. model.set_submodule(module_name, new_module)
  96. has_been_replaced = True
  97. if not has_been_replaced:
  98. logger.warning(
  99. "You are loading your model using eetq but no linear modules were found in your model."
  100. " Please double check your model architecture, or submit an issue on github if you think this is"
  101. " a bug."
  102. )
  103. return model