vptq.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # Copyright 2024 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. "VPTQ (Vector Post-Training Quantization) integration file"
  15. import torch.nn as nn
  16. from accelerate import init_empty_weights
  17. from vptq import VQuantLinear
  18. def replace_with_vptq_linear(
  19. model,
  20. quantization_config=None,
  21. modules_to_not_convert=None,
  22. current_key_name=None,
  23. has_been_replaced=False,
  24. ):
  25. """
  26. Public method that recursively replaces the Linear layers of the given model with VPTQ quantized layers.
  27. `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
  28. conversion has been successful or not.
  29. Args:
  30. model (`torch.nn.Module`):
  31. The model to convert, can be any `torch.nn.Module` instance.
  32. quantization_config (`VptqConfig`):
  33. The quantization config object that contains the quantization parameters.
  34. modules_to_not_convert (`list[`str`]`, *optional*, defaults to `["lm_head"]`):
  35. Names of the modules to not convert in `VQuantLinear`. In practice we keep the `lm_head` in full precision
  36. for numerical stability reasons.
  37. current_key_name (`list`, *optional*):
  38. A list that contains the current key name. This is used for recursion and should not be passed by the user.
  39. has_been_replaced (`bool`, *optional*):
  40. A boolean that indicates if the conversion has been successful or not. This is used for recursion and
  41. should not be passed by the user.
  42. """
  43. modules_to_not_convert = modules_to_not_convert if modules_to_not_convert else ["lm_head"]
  44. for name, module in model.named_children():
  45. if current_key_name is None:
  46. current_key_name = []
  47. current_key_name.append(name)
  48. layer_name = ".".join(current_key_name)
  49. shared_layer_config = quantization_config.shared_layer_config
  50. config_for_layers = quantization_config.config_for_layers
  51. if (
  52. isinstance(module, nn.Linear)
  53. and layer_name not in modules_to_not_convert
  54. and ((layer_name in config_for_layers) or (current_key_name[-1] in shared_layer_config))
  55. ):
  56. layer_params = config_for_layers.get(layer_name, None) or shared_layer_config.get(
  57. current_key_name[-1], None
  58. )
  59. with init_empty_weights():
  60. in_features = module.in_features
  61. out_features = module.out_features
  62. model._modules[name] = VQuantLinear(
  63. in_features,
  64. out_features,
  65. vector_lens=layer_params["vector_lens"],
  66. num_centroids=layer_params["num_centroids"],
  67. num_res_centroids=layer_params["num_res_centroids"],
  68. group_num=layer_params["group_num"],
  69. group_size=layer_params["group_size"],
  70. outlier_size=layer_params["outlier_size"],
  71. indices_as_float=layer_params["indices_as_float"],
  72. enable_norm=layer_params["enable_norm"],
  73. enable_perm=layer_params["enable_perm"],
  74. is_indice_packed=True,
  75. enable_proxy_error=False,
  76. bias=module.bias is not None,
  77. )
  78. has_been_replaced = True
  79. # Force requires grad to False to avoid unexpected errors
  80. model._modules[name].requires_grad_(False)
  81. if len(list(module.children())) > 0:
  82. _, has_been_replaced = replace_with_vptq_linear(
  83. module,
  84. quantization_config=quantization_config,
  85. modules_to_not_convert=modules_to_not_convert,
  86. current_key_name=current_key_name,
  87. has_been_replaced=has_been_replaced,
  88. )
  89. # Remove the last key for recursion
  90. current_key_name.pop(-1)
  91. return model, has_been_replaced