-
Notifications
You must be signed in to change notification settings - Fork 27.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* aqlm init * calibration and dtypes * docs * Readme update * is_aqlm_available * Simpler link in docs * Test TODO real reference * init _import_structure fix * AqlmConfig autodoc * integration aqlm * integrations in tests * docstring fix * legacy typing * Less typings * More kernels information * Performance -> Accuracy * correct tests * remoced multi-gpu test * Update docs/source/en/quantization.md Co-authored-by: Younes Belkada <[email protected]> * Update src/transformers/utils/quantization_config.py Co-authored-by: Arthur <[email protected]> * Brought back multi-gpu tests * Update src/transformers/integrations/aqlm.py Co-authored-by: Marc Sun <[email protected]> * Update tests/quantization/aqlm_integration/test_aqlm.py Co-authored-by: Marc Sun <[email protected]> --------- Co-authored-by: Andrei Panferov <[email protected]> Co-authored-by: Younes Belkada <[email protected]> Co-authored-by: Arthur <[email protected]> Co-authored-by: Marc Sun <[email protected]>
- Loading branch information
1 parent
63ffd56
commit 1ecf5f7
Showing
14 changed files
with
489 additions
and
2 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
# 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. | ||
"AQLM (Additive Quantization of Language Model) integration file" | ||
|
||
|
||
from ..utils import is_accelerate_available, is_aqlm_available, is_torch_available | ||
|
||
|
||
if is_torch_available(): | ||
import torch.nn as nn | ||
|
||
|
||
def replace_with_aqlm_linear( | ||
model, | ||
quantization_config=None, | ||
linear_weights_not_to_quantize=None, | ||
current_key_name=None, | ||
has_been_replaced=False, | ||
): | ||
""" | ||
Public method that recursively replaces the Linear layers of the given model with AQLM 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 (`AqlmConfig`): | ||
The quantization config object that contains the quantization parameters. | ||
linear_weights_not_to_quantize (`list[str]`, *optional*): | ||
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 | ||
converted. | ||
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. | ||
""" | ||
if not is_aqlm_available(): | ||
raise ValueError("AQLM is not available. Please install it with `pip install aqlm[cpu,gpu]`") | ||
|
||
if not is_accelerate_available(): | ||
raise ValueError("AQLM requires Accelerate to be installed: `pip install accelerate`") | ||
|
||
if linear_weights_not_to_quantize is None: | ||
linear_weights_not_to_quantize = [] | ||
|
||
from accelerate import init_empty_weights | ||
from aqlm import QuantizedLinear | ||
|
||
for name, module in model.named_children(): | ||
if current_key_name is None: | ||
current_key_name = [] | ||
current_key_name.append(name) | ||
|
||
if isinstance(module, nn.Linear): | ||
# Check if the current key is not in the `linear_weights_not_to_quantize` | ||
if ".".join(current_key_name) + ".weight" not in linear_weights_not_to_quantize: | ||
with init_empty_weights(): | ||
in_features = module.in_features | ||
out_features = module.out_features | ||
|
||
model._modules[name] = QuantizedLinear( | ||
in_features, | ||
out_features, | ||
bias=module.bias is not None, | ||
in_group_size=quantization_config.in_group_size, | ||
out_group_size=quantization_config.out_group_size, | ||
num_codebooks=quantization_config.num_codebooks, | ||
nbits_per_codebook=quantization_config.nbits_per_codebook, | ||
) | ||
has_been_replaced = True | ||
|
||
# Store the module class in case we need to transpose the weight later | ||
model._modules[name].source_cls = type(module) | ||
# 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_aqlm_linear( | ||
module, | ||
quantization_config=quantization_config, | ||
linear_weights_not_to_quantize=linear_weights_not_to_quantize, | ||
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,89 @@ | ||
# 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 ..integrations import replace_with_aqlm_linear | ||
from ..utils import is_accelerate_available, is_aqlm_available, is_torch_available, logging | ||
from ..utils.quantization_config import QuantizationConfigMixin | ||
|
||
|
||
if is_torch_available(): | ||
import torch | ||
|
||
logger = logging.get_logger(__name__) | ||
|
||
|
||
class AqlmHfQuantizer(HfQuantizer): | ||
""" | ||
Quantizer of the AQLM method. Enables the loading of prequantized models. | ||
""" | ||
|
||
requires_calibration = True | ||
required_packages = ["aqlm"] | ||
optimum_quantizer = None | ||
|
||
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 `aqlm` quantization requires Accelerate: `pip install accelerate`") | ||
|
||
if not is_aqlm_available(): | ||
raise ImportError("Using `aqlm` quantization requires AQLM: `pip install aqlm[gpu,cpu]`") | ||
|
||
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 AQLM inference on GPU and loading the model in `torch.float16`. To overwrite it, set `torch_dtype` manually." | ||
) | ||
else: | ||
torch_dtype = torch.float32 | ||
logger.info( | ||
"CUDA is unavailable. Assuming AQLM inference on CPU and loading the model in `torch.float32`. To overwrite it, set `torch_dtype` manually." | ||
) | ||
return torch_dtype | ||
|
||
def _process_model_before_weight_loading( | ||
self, | ||
model: "PreTrainedModel", | ||
**kwargs, | ||
): | ||
replace_with_aqlm_linear( | ||
model, | ||
quantization_config=self.quantization_config, | ||
linear_weights_not_to_quantize=self.quantization_config.linear_weights_not_to_quantize, | ||
) | ||
model.config.quantization_config = self.quantization_config | ||
|
||
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): | ||
model._is_quantized_training_enabled = False | ||
return model | ||
|
||
@property | ||
def is_trainable(self, model: Optional["PreTrainedModel"] = None): | ||
return False | ||
|
||
@property | ||
def is_serializable(self): | ||
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
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.