vptq.py 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. 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. def replace_with_vptq_linear(model, modules_to_not_convert: list[str] | None = None, quantization_config=None):
  22. """
  23. Public method that replaces the Linear layers of the given model with SPQR quantized layers.
  24. Args:
  25. model (`torch.nn.Module`):
  26. The model to convert, can be any `torch.nn.Module` instance.
  27. modules_to_not_convert (`list[str]`, *optional*, defaults to `None`):
  28. 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
  29. converted.
  30. quantization_config (`VptqConfig`):
  31. The quantization config object that contains the quantization parameters.
  32. """
  33. from vptq import VQuantLinear
  34. has_been_replaced = False
  35. shared_layer_config = quantization_config.shared_layer_config
  36. config_for_layers = quantization_config.config_for_layers
  37. for module_name, module in model.named_modules():
  38. if not should_convert_module(module_name, modules_to_not_convert):
  39. continue
  40. with torch.device("meta"):
  41. if isinstance(module, nn.Linear):
  42. layer_params = config_for_layers.get(module_name, None) or shared_layer_config.get(
  43. module_name.rsplit(".")[1], None
  44. )
  45. new_module = VQuantLinear(
  46. module.in_features,
  47. module.out_features,
  48. vector_lens=layer_params["vector_lens"],
  49. num_centroids=layer_params["num_centroids"],
  50. num_res_centroids=layer_params["num_res_centroids"],
  51. group_num=layer_params["group_num"],
  52. group_size=layer_params["group_size"],
  53. outlier_size=layer_params["outlier_size"],
  54. indices_as_float=layer_params["indices_as_float"],
  55. enable_norm=layer_params["enable_norm"],
  56. enable_perm=layer_params["enable_perm"],
  57. is_indice_packed=True,
  58. enable_proxy_error=False,
  59. bias=module.bias is not None,
  60. )
  61. # Force requires grad to False to avoid unexpected errors
  62. model._modules[module_name].requires_grad_(False)
  63. model.set_submodule(module_name, new_module)
  64. has_been_replaced = True
  65. if not has_been_replaced:
  66. logger.warning(
  67. "You are loading your model using eetq but no linear modules were found in your model."
  68. " Please double check your model architecture, or submit an issue on github if you think this is"
  69. " a bug."
  70. )
  71. return model