-
Notifications
You must be signed in to change notification settings - Fork 27.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
FEAT : Adding VPTQ quantization method to HFQuantizer (#34770)
* init vptq * add integration * add vptq support fix readme * add tests && format * format * address comments * format * format * address comments * format * address comments * remove debug code * Revert "remove debug code" This reverts commit ed3b3ea. * fix test --------- Co-authored-by: Yang Wang <wyatuestc@gmail.com>
- Loading branch information
1 parent
5a2aedc
commit 4e27a40
Showing
21 changed files
with
647 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
# Copyright 2024 The HuggingFace Team. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
"VPTQ (Vector Post-Training Quantization) integration file" | ||
|
||
import torch.nn as nn | ||
from accelerate import init_empty_weights | ||
from vptq import VQuantLinear | ||
|
||
|
||
def replace_with_vptq_linear( | ||
model, | ||
quantization_config=None, | ||
modules_to_not_convert=None, | ||
current_key_name=None, | ||
has_been_replaced=False, | ||
): | ||
""" | ||
Public method that recursively replaces the Linear layers of the given model with VPTQ quantized layers. | ||
`accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the | ||
conversion has been successfull or not. | ||
Args: | ||
model (`torch.nn.Module`): | ||
The model to convert, can be any `torch.nn.Module` instance. | ||
quantization_config (`VptqConfig`): | ||
The quantization config object that contains the quantization parameters. | ||
modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`): | ||
Names of the modules to not convert in `VQuantLinear`. In practice we keep the `lm_head` in full precision | ||
for numerical stability reasons. | ||
current_key_name (`list`, *optional*): | ||
A list that contains the current key name. This is used for recursion and should not be passed by the user. | ||
has_been_replaced (`bool`, *optional*): | ||
A boolean that indicates if the conversion has been successful or not. This is used for recursion and | ||
should not be passed by the user. | ||
""" | ||
|
||
modules_to_not_convert = ["lm_head"] if not modules_to_not_convert else modules_to_not_convert | ||
|
||
for name, module in model.named_children(): | ||
if current_key_name is None: | ||
current_key_name = [] | ||
current_key_name.append(name) | ||
layer_name = ".".join(current_key_name) | ||
shared_layer_config = quantization_config.shared_layer_config | ||
config_for_layers = quantization_config.config_for_layers | ||
|
||
if ( | ||
isinstance(module, nn.Linear) | ||
and layer_name not in modules_to_not_convert | ||
and ((layer_name in config_for_layers) or (current_key_name[-1] in shared_layer_config)) | ||
): | ||
layer_params = config_for_layers.get(layer_name, None) or shared_layer_config.get( | ||
current_key_name[-1], None | ||
) | ||
|
||
with init_empty_weights(): | ||
in_features = module.in_features | ||
out_features = module.out_features | ||
|
||
model._modules[name] = VQuantLinear( | ||
in_features, | ||
out_features, | ||
vector_lens=layer_params["vector_lens"], | ||
num_centroids=layer_params["num_centroids"], | ||
num_res_centroids=layer_params["num_res_centroids"], | ||
group_num=layer_params["group_num"], | ||
group_size=layer_params["group_size"], | ||
outlier_size=layer_params["outlier_size"], | ||
indices_as_float=layer_params["indices_as_float"], | ||
enable_norm=layer_params["enable_norm"], | ||
enable_perm=layer_params["enable_perm"], | ||
is_indice_packed=True, | ||
enable_proxy_error=False, | ||
bias=module.bias is not None, | ||
) | ||
has_been_replaced = True | ||
|
||
# Force requires grad to False to avoid unexpected errors | ||
model._modules[name].requires_grad_(False) | ||
if len(list(module.children())) > 0: | ||
_, has_been_replaced = replace_with_vptq_linear( | ||
module, | ||
quantization_config=quantization_config, | ||
modules_to_not_convert=modules_to_not_convert, | ||
current_key_name=current_key_name, | ||
has_been_replaced=has_been_replaced, | ||
) | ||
# Remove the last key for recursion | ||
current_key_name.pop(-1) | ||
return model, has_been_replaced |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
from typing import TYPE_CHECKING, Optional | ||
|
||
from .base import HfQuantizer | ||
|
||
|
||
if TYPE_CHECKING: | ||
from ..modeling_utils import PreTrainedModel | ||
|
||
from ..utils import is_accelerate_available, is_torch_available, is_vptq_available, logging | ||
from ..utils.quantization_config import QuantizationConfigMixin | ||
|
||
|
||
if is_torch_available(): | ||
import torch | ||
|
||
logger = logging.get_logger(__name__) | ||
|
||
|
||
class VptqHfQuantizer(HfQuantizer): | ||
""" | ||
Quantizer of the VPTQ method. Enables the loading of prequantized models. | ||
""" | ||
|
||
requires_calibration = True | ||
required_packages = ["vptq"] | ||
|
||
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): | ||
super().__init__(quantization_config, **kwargs) | ||
self.quantization_config = quantization_config | ||
|
||
def validate_environment(self, *args, **kwargs): | ||
if not is_accelerate_available(): | ||
raise ImportError("Using `vptq` quantization requires Accelerate: `pip install accelerate`") | ||
|
||
if not is_vptq_available(): | ||
raise ImportError("Using `vptq` quantization requires VPTQ>=0.0.4: `pip install -U vptq`") | ||
|
||
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype": | ||
if torch_dtype is None: | ||
if torch.cuda.is_available(): | ||
torch_dtype = torch.float16 | ||
logger.info( | ||
"CUDA available. Assuming VPTQ inference on GPU and loading the model in `torch.float16`. To overwrite it, set `torch_dtype` manually." | ||
) | ||
else: | ||
import vptq | ||
|
||
device_availability = getattr(vptq, "device_availability", lambda device: False) | ||
if device_availability("cpu") is True: | ||
raise RuntimeError("No GPU found. Please wait for the next release of VPTQ to use CPU inference") | ||
torch_dtype = torch.float32 | ||
logger.info("No GPU found. Assuming VPTQ inference on CPU and loading the model in `torch.float32`.") | ||
return torch_dtype | ||
|
||
def _process_model_before_weight_loading( | ||
self, | ||
model: "PreTrainedModel", | ||
**kwargs, | ||
): | ||
""" | ||
we don't have param like modules_to_not_convert to indicate which layers should not be quantized | ||
because `quantization_config` include the layers that should be quantized | ||
""" | ||
from ..integrations import replace_with_vptq_linear | ||
|
||
modules_to_not_convert = kwargs.get("modules_to_not_convert", []) + ( | ||
self.quantization_config.modules_to_not_convert or [] | ||
) | ||
|
||
replace_with_vptq_linear( | ||
model, | ||
quantization_config=self.quantization_config, | ||
modules_to_not_convert=modules_to_not_convert, | ||
) | ||
model.config.quantization_config = self.quantization_config | ||
|
||
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): | ||
return model | ||
|
||
@property | ||
def is_trainable(self, model: Optional["PreTrainedModel"] = None): | ||
return False | ||
|
||
def is_serializable(self, safe_serialization=None): | ||
return True |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.