|
| 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 | + |
| 16 | +from ..utils import is_accelerate_available, is_spqr_available, is_torch_available |
| 17 | + |
| 18 | + |
| 19 | +if is_torch_available(): |
| 20 | + import torch.nn as nn |
| 21 | + |
| 22 | + |
| 23 | +def replace_with_spqr_linear( |
| 24 | + model, |
| 25 | + quantization_config=None, |
| 26 | + modules_to_not_convert=None, |
| 27 | + current_key_name=None, |
| 28 | + has_been_replaced=False, |
| 29 | +): |
| 30 | + """ |
| 31 | + Public method that recursively replaces the Linear layers of the given model with SpQR quantized layers. |
| 32 | + `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the |
| 33 | + conversion has been successful or not. |
| 34 | +
|
| 35 | + Args: |
| 36 | + model (`torch.nn.Module`): |
| 37 | + The model to convert, can be any `torch.nn.Module` instance. |
| 38 | + quantization_config (`SpQRConfig`): |
| 39 | + The quantization config object that contains the quantization parameters. |
| 40 | + modules_to_not_convert (`list[str]`, *optional*): |
| 41 | + 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 |
| 42 | + converted. |
| 43 | + current_key_name (`list`, *optional*): |
| 44 | + A list that contains the current key name. This is used for recursion and should not be passed by the user. |
| 45 | + has_been_replaced (`bool`, *optional*): |
| 46 | + A boolean that indicates if the conversion has been successful or not. This is used for recursion and |
| 47 | + should not be passed by the user. |
| 48 | + """ |
| 49 | + if modules_to_not_convert is None: |
| 50 | + modules_to_not_convert = [] |
| 51 | + |
| 52 | + if is_accelerate_available(): |
| 53 | + from accelerate import init_empty_weights |
| 54 | + if is_spqr_available(): |
| 55 | + from spqr_quant import QuantizedLinear |
| 56 | + |
| 57 | + for name, module in model.named_children(): |
| 58 | + if current_key_name is None: |
| 59 | + current_key_name = [] |
| 60 | + current_key_name.append(name) |
| 61 | + |
| 62 | + if isinstance(module, nn.Linear): |
| 63 | + # Check if the current key is not in the `modules_to_not_convert` |
| 64 | + if ".".join(current_key_name) + ".weight" not in modules_to_not_convert: |
| 65 | + with init_empty_weights(): |
| 66 | + tensor_name = ".".join(current_key_name) |
| 67 | + |
| 68 | + shapes = quantization_config.shapes |
| 69 | + shapes_keys = shapes.keys() |
| 70 | + |
| 71 | + shapes_valid = ( |
| 72 | + f"{tensor_name}.dense_weights.shape" in shapes_keys |
| 73 | + and f"{tensor_name}.row_offsets.shape" in shapes_keys |
| 74 | + and f"{tensor_name}.col_vals.shape" in shapes_keys |
| 75 | + and f"{tensor_name}.in_perm.shape" in shapes_keys |
| 76 | + ) |
| 77 | + |
| 78 | + if not shapes_valid: |
| 79 | + raise ValueError( |
| 80 | + f"The SpQR quantization config does not contain the shape " |
| 81 | + f"configuration for {tensor_name}. This indicates that the " |
| 82 | + f"configuration is either invalid or corrupted." |
| 83 | + ) |
| 84 | + |
| 85 | + dense_weights_shape = shapes[f"{tensor_name}.dense_weights.shape"] |
| 86 | + row_offsets_shape = shapes[f"{tensor_name}.row_offsets.shape"] |
| 87 | + col_vals_shape = shapes[f"{tensor_name}.col_vals.shape"] |
| 88 | + in_perm_shape = shapes[f"{tensor_name}.in_perm.shape"] |
| 89 | + |
| 90 | + in_features = module.in_features |
| 91 | + out_features = module.out_features |
| 92 | + |
| 93 | + model._modules[name] = QuantizedLinear.create_placehodler( |
| 94 | + rows=out_features, |
| 95 | + cols=in_features, |
| 96 | + bits=quantization_config.bits, |
| 97 | + beta1=quantization_config.beta1, |
| 98 | + beta2=quantization_config.beta2, |
| 99 | + dense_weights_shape=dense_weights_shape, |
| 100 | + row_offsets_shape=row_offsets_shape, |
| 101 | + col_vals_shape=col_vals_shape, |
| 102 | + in_perm_shape=in_perm_shape, |
| 103 | + ) |
| 104 | + has_been_replaced = True |
| 105 | + |
| 106 | + # Store the module class in case we need to transpose the weight later |
| 107 | + model._modules[name].source_cls = type(module) |
| 108 | + # Force requires grad to False to avoid unexpected errors |
| 109 | + model._modules[name].requires_grad_(False) |
| 110 | + else: |
| 111 | + pass |
| 112 | + if len(list(module.children())) > 0: |
| 113 | + _, has_been_replaced = replace_with_spqr_linear( |
| 114 | + module, |
| 115 | + quantization_config=quantization_config, |
| 116 | + modules_to_not_convert=modules_to_not_convert, |
| 117 | + current_key_name=current_key_name, |
| 118 | + has_been_replaced=has_been_replaced, |
| 119 | + ) |
| 120 | + # Remove the last key for recursion |
| 121 | + current_key_name.pop(-1) |
| 122 | + return model, has_been_replaced |
0 commit comments