spqr.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "SpQR (Sparse-Quantized Representation) integration file"
  15. from ..quantizers.quantizers_utils import should_convert_module
  16. from ..utils import is_spqr_available, 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_spqr_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 (`SpQRConfig`):
  31. The quantization config object that contains the quantization parameters.
  32. """
  33. if is_spqr_available():
  34. from spqr_quant import QuantizedLinear
  35. has_been_replaced = False
  36. # we need this to correctly materialize the weights during quantization
  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. shapes = quantization_config.shapes
  43. new_module = QuantizedLinear.create_placehodler(
  44. rows=module.out_features,
  45. cols=module.in_features,
  46. bits=quantization_config.bits,
  47. beta1=quantization_config.beta1,
  48. beta2=quantization_config.beta2,
  49. dense_weights_shape=shapes[f"{module_name}.dense_weights.shape"],
  50. row_offsets_shape=shapes[f"{module_name}.row_offsets.shape"],
  51. col_vals_shape=shapes[f"{module_name}.col_vals.shape"],
  52. in_perm_shape=shapes[f"{module_name}.in_perm.shape"],
  53. )
  54. # Force requires grad to False to avoid unexpected errors
  55. model._modules[module_name].requires_grad_(False)
  56. model.set_submodule(module_name, new_module)
  57. has_been_replaced = True
  58. if not has_been_replaced:
  59. logger.warning(
  60. "You are loading your model using eetq but no linear modules were found in your model."
  61. " Please double check your model architecture, or submit an issue on github if you think this is"
  62. " a bug."
  63. )
  64. return model