
    g'                         d dl mZmZ d dlmZmZmZmZmZm	Z	 ddl
mZ ddlmZ erddlmZ  e            rd dlZ G d d	e          ZdS )
    )ABCabstractmethod)TYPE_CHECKINGAnyDictListOptionalUnion   )is_torch_available)QuantizationConfigMixin)PreTrainedModelNc            
          e Zd ZdZdZdZdZdefdZd(d	Z	d
e
eeef                  de
eeef                  fdZd(dZdee         dedee         fdZdee         dee         dee         fdZdddeedf         fdZdeeeeef         f         deeeeef         f         fdZdddddedeeef         def
dZd)dZd Zd*d Zd*d!Zd" Zd# Zed$             Z ed%             Z!ed+d&            Z"e#ed'                         Z$dS ),HfQuantizera  
    Abstract class of the HuggingFace quantizer. Supports for now quantizing HF transformers models for inference and/or quantization.
    This class is used only for transformers.PreTrainedModel.from_pretrained and cannot be easily used outside the scope of that method
    yet.

    Attributes
        quantization_config (`transformers.utils.quantization_config.QuantizationConfigMixin`):
            The quantization config that defines the quantization parameters of your model that you want to quantize.
        modules_to_not_convert (`List[str]`, *optional*):
            The list of module names to not convert when quantizing the model.
        required_packages (`List[str]`, *optional*):
            The list of required pip packages to install prior to using the quantizer
        requires_calibration (`bool`):
            Whether the quantization method requires to calibrate the model before using it.
        requires_parameters_quantization (`bool`):
            Whether the quantization method requires to create a new Parameter. For example, for bitsandbytes, it is
            required to create a new xxxParameter in order to properly quantize the model.
    FNquantization_configc                     || _         |                    dg           | _        |                    dd          | _        | j        s| j        rt          d|j         d          d S d S )Nmodules_to_not_convertpre_quantizedTzThe quantization method z does require the model to be pre-quantized. You explicitly passed `pre_quantized=False` meaning your model weights are not quantized. Make sure to pass `pre_quantized=True` while knowing what you are doing.)r   popr   r   requires_calibration
ValueErrorquant_method)selfr   kwargss      X/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/quantizers/base.py__init__zHfQuantizer.__init__4   s    #6  '-jj1I2&N&N##ZZ>>! 	d&? 	O+>+K O O O  	 	 	 	    torch_dtypetorch.dtypereturnc                     |S )aU  
        Some quantization methods require to explicitly set the dtype of the model to a
        target dtype. You need to override this method in case you want to make sure that behavior is
        preserved

        Args:
            torch_dtype (`torch.dtype`):
                The input dtype that is passed in `from_pretrained`
         r   r   s     r   update_torch_dtypezHfQuantizer.update_torch_dtypeB   
     r   
device_mapc                     |S )a  
        Override this method if you want to pass a override the existing device map with a new
        one. E.g. for bitsandbytes, since `accelerate` is a hard requirement, if no device_map is
        passed, the device_map is set to `"auto"``

        Args:
            device_map (`Union[dict, str]`, *optional*):
                The device_map that is passed through the `from_pretrained` method.
        r"   )r   r&   s     r   update_device_mapzHfQuantizer.update_device_mapN   s
     r   c                     |S )a  
        Override this method if you want to adjust the `target_dtype` variable used in `from_pretrained`
        to compute the device_map in case the device_map is a `str`. E.g. for bitsandbytes we force-set `target_dtype`
        to `torch.int8` and for 4-bit we pass a custom enum `accelerate.CustomDtype.int4`.

        Args:
            torch_dtype (`torch.dtype`, *optional*):
                The torch_dtype that is used to compute the device_map.
        r"   r#   s     r   adjust_target_dtypezHfQuantizer.adjust_target_dtypeZ   r%   r   missing_keysprefixc                     |S )z
        Override this method if you want to adjust the `missing_keys`.

        Args:
            missing_keys (`List[str]`, *optional*):
                The list of missing keys in the checkpoint compared to the state dict of the model
        r"   )r   modelr+   r,   s       r   update_missing_keyszHfQuantizer.update_missing_keysf   s
     r   expected_keysloaded_keysc                     |S )aV  
        Override this method if you want to adjust the `update_expected_keys`.

        Args:
            expected_keys (`List[str]`, *optional*):
                The list of the expected keys in the initialized model.
            loaded_keys (`List[str]`, *optional*):
                The list of the loaded keys in the checkpoint.
        r"   )r   r.   r0   r1   s       r   update_expected_keysz HfQuantizer.update_expected_keysp   s
     r   c                 H      fd|                                 D             S )a  
        returns dtypes for modules that are not quantized - used for the computation of the device_map in case
        one passes a str as a device_map. The method will use the `modules_to_not_convert` that is modified
        in `_process_model_before_weight_loading`.

        Args:
            model (`~transformers.PreTrainedModel`):
                The model to quantize
            torch_dtype (`torch.dtype`):
                The dtype passed in `from_pretrained` method.
        c                 ^    i | ](\  }t          fd j        D                       %)S )c              3       K   | ]}|v V  	d S Nr"   ).0mnames     r   	<genexpr>zCHfQuantizer.get_special_dtypes_update.<locals>.<dictcomp>.<genexpr>   s'      BB19BBBBBBr   )anyr   )r8   _r:   r   r   s     @r   
<dictcomp>z9HfQuantizer.get_special_dtypes_update.<locals>.<dictcomp>   sV     
 
 
aBBBBd&ABBBBB
+
 
 
r   )named_parameters)r   r.   r   s   ` `r   get_special_dtypes_updatez%HfQuantizer.get_special_dtypes_update|   s@    
 
 
 
 
 1133
 
 
 	
r   
max_memoryc                     |S )zaadjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantizationr"   )r   rA   s     r   adjust_max_memoryzHfQuantizer.adjust_max_memory   s    r   r.   r   param_valueztorch.Tensor
param_name
state_dictc                     dS )a  
        checks if a loaded state_dict component is part of quantized param + some validation; only defined if
        requires_parameters_quantization == True for quantization methods that require to create a new parameters
        for quantization.
        Fr"   )r   r.   rD   rE   rF   r   s         r   check_quantized_paramz!HfQuantizer.check_quantized_param   s	     ur   torch.nn.Parameterc                 N    | j         st          d| j        j         d          dS )z
        takes needed components from state_dict and creates quantized param; only applicable if
        requires_parameters_quantization == True
        zG`.create_quantized_param()` method is not supported by quantizer class .N) requires_parameters_quantizationAttributeError	__class____name__r   argsr   s      r   create_quantized_paramz"HfQuantizer.create_quantized_param   s@    
 4 	 tZ^ZhZqttt  	 	r   c                     dS )a&  
        This method is used to potentially check for potential conflicts with arguments that are
        passed in `from_pretrained`. You need to define it for all future quantizers that are integrated with transformers.
        If no explicit check are needed, simply return nothing.
        Nr"   rP   s      r   validate_environmentz HfQuantizer.validate_environment   s	     	r   c                 N    d|_         | j        j        |_         | j        |fi |S )aQ  
        Setting model attributes and/or converting model before weights loading. At this point
        the model should be initialized on the meta device so you can freely manipulate the skeleton
        of the model in order to replace modules in-place. Make sure to override the abstract method `_process_model_before_weight_loading`.

        Args:
            model (`~transformers.PreTrainedModel`):
                The model to quantize
            kwargs (`dict`, *optional*):
                The keyword arguments that are passed along `_process_model_before_weight_loading`.
        T)is_quantizedr   r   quantization_method$_process_model_before_weight_loadingr   r.   r   s      r   preprocess_modelzHfQuantizer.preprocess_model   s5     "$($<$I!8t8II&IIIr   c                      | j         |fi |S )a  
        Post-process the model post weights loading.
        Make sure to override the abstract method `_process_model_after_weight_loading`.

        Args:
            model (`~transformers.PreTrainedModel`):
                The model to quantize
            kwargs (`dict`, *optional*):
                The keyword arguments that are passed along `_process_model_after_weight_loading`.
        )#_process_model_after_weight_loadingrY   s      r   postprocess_modelzHfQuantizer.postprocess_model   s     8t7HHHHHr   c                 4    |                      |          }|`|S )z
        Potentially dequantize the model to retrive the original model, with some loss in accuracy / performance.
        Note not all quantization schemes support this.
        )_dequantizehf_quantizerr   r.   s     r   
dequantizezHfQuantizer.dequantize   s$    
   '' r   c                 :    t          | j        j         d          )NzH has no implementation of `dequantize`, please raise an issue on GitHub.)NotImplementedErrorr   r   ra   s     r   r_   zHfQuantizer._dequantize   s&    !'4~~~
 
 	
r   c                     d S r7   r"   rY   s      r   rX   z0HfQuantizer._process_model_before_weight_loading   s    EHSr   c                     d S r7   r"   rY   s      r   r\   z/HfQuantizer._process_model_after_weight_loading   s    DGCr   c                     d S r7   r"   )r   safe_serializations     r   is_serializablezHfQuantizer.is_serializable   s    8;r   c                     d S r7   r"   )r   s    r   is_trainablezHfQuantizer.is_trainable   s    Cr   )r   r   r    r   )r    rI   )r.   r   r7   )%rO   
__module____qualname____doc__r   required_packagesrL   r   r   r$   r	   r   strr   r(   r*   r   r/   r3   r@   r
   intrC   boolrH   rR   rT   rZ   r]   rb   r_   r   rX   r\   ri   propertyrk   r"   r   r   r   r      s        & !',$,C    
 
 
 

HT#s(^,D 
RVWZ\_W_R`Ia 
 
 
 

 
 
 
tCy # RVWZR[    
c 
QUVYQZ 
_cdg_h 
 
 
 

M 
dSVXeSeNf 
 
 
 
&DeCHo1E,F 4PSUZ[^`c[cUdPdKe      $ 	
 cN 
        J J J J I I I I
 
 

 
 

 HH ^HGG ^G;;; ^; ^ Xr   r   )abcr   r   typingr   r   r   r   r	   r
   utilsr   utils.quantization_configr   modeling_utilsr   torchr   r"   r   r   <module>rz      s    $ # # # # # # # B B B B B B B B B B B B B B B B & & & & & & ? ? ? ? ? ?  1000000 LLLQ  Q  Q  Q  Q # Q  Q  Q  Q  Q r   