U
    9%eL                     @   s   d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
mZmZmZmZ d dlmZ ddlmZmZ e r~d dlZeeZG dd	 d	eeZeG d
d dZeG dd deZeG dd deZdS )    N)	dataclass)Enum)AnyDictListOptionalUnion)version   )is_torch_availableloggingc                   @   s   e Zd ZdZdZdS )QuantizationMethodbitsandbytesZgptqN)__name__
__module____qualname__BITS_AND_BYTESGPTQ r   r   e/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/utils/quantization_config.pyr   %   s   r   c                   @   sp   e Zd ZU dZeed< edddZee	e
jf dddZee	ef d	d
dZdd Zdee	dddZdS )QuantizationConfigMixinz-
    Mixin class for quantization config
    quant_methodFc                 K   sj   | f |}g }|  D ](\}}t||rt||| || q|D ]}||d qD|rb||fS |S dS )a  
        Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.

        Args:
            config_dict (`Dict[str, Any]`):
                Dictionary that will be used to instantiate the configuration object.
            return_unused_kwargs (`bool`,*optional*, defaults to `False`):
                Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
                `PreTrainedModel`.
            kwargs (`Dict[str, Any]`):
                Additional parameters from which to initialize the configuration object.

        Returns:
            [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
        N)itemshasattrsetattrappendpop)clsconfig_dictZreturn_unused_kwargskwargsconfigZ	to_removekeyvaluer   r   r   	from_dict2   s    

z!QuantizationConfigMixin.from_dict)json_file_pathc              	   C   sD   t |ddd,}|  }tj|dddd }|| W 5 Q R X dS )	a  
        Save this instance to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file in which this configuration instance's parameters will be saved.
            use_diff (`bool`, *optional*, defaults to `True`):
                If set to `True`, only the difference between the config instance and the default
                `QuantizationConfig()` is serialized to JSON file.
        wzutf-8)encodingr
   Tindent	sort_keys
N)opento_dictjsondumpswrite)selfr$   writerr   Zjson_stringr   r   r   to_json_fileS   s    z$QuantizationConfigMixin.to_json_filereturnc                 C   s   t | jS )
        Serializes this instance to a Python dictionary. Returns:
            `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
        )copydeepcopy__dict__r0   r   r   r   r,   d   s    zQuantizationConfigMixin.to_dictc                 C   s   | j j d|   S )N )	__class__r   to_json_stringr9   r   r   r   __repr__k   s    z QuantizationConfigMixin.__repr__T)use_diffr4   c                 C   s.   |dkr|   }n|  }tj|dddd S )a  
        Serializes this instance to a JSON string.

        Args:
            use_diff (`bool`, *optional*, defaults to `True`):
                If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
                is serialized to JSON string.

        Returns:
            `str`: String containing all the attributes that make up this configuration instance in JSON format.
        Tr
   r'   r*   )to_diff_dictr,   r-   r.   )r0   r>   r   r   r   r   r<   n   s    
z&QuantizationConfigMixin.to_json_stringN)F)T)r   r   r   __doc__r   __annotations__classmethodr#   r   strosPathLiker2   r   r   r,   r=   boolr<   r   r   r   r   r   *   s   
 r   c                	   @   sf   e Zd ZdZdddZdd	 Zd
d Zdd Zee	e
f dddZdd Zee	e
f dddZdS )BitsAndBytesConfiga  
    This is a wrapper class about all possible attributes and features that you can play with a model that has been
    loaded using `bitsandbytes`.

    This replaces `load_in_8bit` or `load_in_4bit`therefore both options are mutually exclusive.

    Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
    then more arguments will be added to this class.

    Args:
        load_in_8bit (`bool`, *optional*, defaults to `False`):
            This flag is used to enable 8-bit quantization with LLM.int8().
        load_in_4bit (`bool`, *optional*, defaults to `False`):
            This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
            `bitsandbytes`.
        llm_int8_threshold (`float`, *optional*, defaults to 6):
            This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
            Multiplication for Transformers at Scale` paper: https://arxiv.org/abs/2208.07339 Any hidden states value
            that is above this threshold will be considered an outlier and the operation on those values will be done
            in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but
            there are some exceptional systematic outliers that are very differently distributed for large models.
            These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of
            magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6,
            but a lower threshold might be needed for more unstable models (small models, fine-tuning).
        llm_int8_skip_modules (`List[str]`, *optional*):
            An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as
            Jukebox that has several heads in different places and not necessarily at the last position. For example
            for `CausalLM` models, the last `lm_head` is kept in its original `dtype`.
        llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`):
            This flag is used for advanced use cases and users that are aware of this feature. If you want to split
            your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use
            this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8
            operations will not be run on CPU.
        llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`):
            This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not
            have to be converted back and forth for the backward pass.
        bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`):
            This sets the computational type which might be different than the input time. For example, inputs might be
            fp32, but computation can be set to bf16 for speedups.
        bnb_4bit_quant_type (`str`, {fp4, nf4}, defaults to `fp4`):
            This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types
            which are specified by `fp4` or `nf4`.
        bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`):
            This flag is used for nested quantization where the quantization constants from the first quantization are
            quantized again.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional parameters from which to initialize the configuration object.
    F      @Nfp4c
                 K   s   t j| _|| _|| _|| _|| _|| _|| _|| _	|	| _
|d krJtj| _n4t|trbtt|| _nt|tjrv|| _ntd|   d S )Nz8bnb_4bit_compute_dtype must be a string or a torch.dtype)r   r   r   load_in_8bitload_in_4bitllm_int8_thresholdllm_int8_skip_modules llm_int8_enable_fp32_cpu_offloadllm_int8_has_fp16_weightbnb_4bit_quant_typebnb_4bit_use_double_quanttorchZfloat32bnb_4bit_compute_dtype
isinstancerC   getattrdtype
ValueError	post_init)r0   rJ   rK   rL   rM   rN   rO   rS   rP   rQ   r   r   r   r   __init__   s"    

zBitsAndBytesConfig.__init__c                 C   s   t | jtstd| jdk	r2t | jts2tdt | jtsFtdt | jtsZtd| j	dk	rzt | j	t
jsztdt | jtstdt | jtstd| jrttjd	td
kstddS )z~
        Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
        z"llm_int8_threshold must be a floatNz/llm_int8_skip_modules must be a list of stringsz2llm_int8_enable_fp32_cpu_offload must be a booleanz*llm_int8_has_fp16_weight must be a booleanz*bnb_4bit_compute_dtype must be torch.dtypez$bnb_4bit_quant_type must be a stringz+bnb_4bit_use_double_quant must be a booleanr   z0.39.0z[4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version)rT   rL   floatrW   rM   listrN   rF   rO   rS   rR   rV   rP   rC   rQ   rK   r	   parse	importlibmetadatar9   r   r   r   rX      s(    zBitsAndBytesConfig.post_initc                 C   s   | j p
| jS )zP
        Returns `True` if the model is quantizable, `False` otherwise.
        )rJ   rK   r9   r   r   r   is_quantizable   s    z!BitsAndBytesConfig.is_quantizablec                 C   s:   | j r
dS | jr| jdkrdS | jr2| jdkr2dS dS dS )z
        This method returns the quantization method used for the model. If the model is not quantizable, it returns
        `None`.
        Zllm_int8rI   Znf4N)rJ   rK   rP   r9   r   r   r   quantization_method   s    z&BitsAndBytesConfig.quantization_methodr3   c                 C   s*   t | j}t|d dd |d< |S )r5   rS   .   )r6   r7   r8   rC   split)r0   outputr   r   r   r,   	  s    zBitsAndBytesConfig.to_dictc                 C   s(   |   }| jj dtj|ddd dS )Nr:   r
   Tr'   r*   )r,   r;   r   r-   r.   )r0   r   r   r   r   r=     s    zBitsAndBytesConfig.__repr__c                 C   s@   |   }t   }i }| D ]\}}||| kr|||< q|S )a'  
        Removes all attributes from config which correspond to the default config attributes for better readability and
        serializes to a Python dictionary.

        Returns:
            `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
        )r,   rG   r   )r0   r   Zdefault_config_dictZserializable_config_dictr!   r"   r   r   r   r?     s    

zBitsAndBytesConfig.to_diff_dict)	FFrH   NFFNrI   F)r   r   r   r@   rY   rX   r_   r`   r   rC   r   r,   r=   r?   r   r   r   r   rG      s"   3         
"
rG   c                   @   sv   e Zd ZdZdeeeeee	 e	f  ee
eeeeee ee	 eee	  eee eee dd	d
Zdd Zdd ZdS )
GPTQConfiga  
    This is a wrapper class about all possible attributes and features that you can play with a model that has been
    loaded using `optimum` api for gptq quantization relying on auto_gptq backend.

    Args:
        bits (`int`):
            The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
        tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*):
            The tokenizer used to process the dataset. You can pass either:
                - A custom tokenizer object.
                - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
                    Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
                    user or organization name, like `dbmdz/bert-base-german-cased`.
                - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
                    using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
        dataset (`Union[List[str]]`, *optional*):
            The dataset used for quantization. You can provide your own dataset in a list of string or just use the
            original datasets used in GPTQ paper ['wikitext2','c4','c4-new','ptb','ptb-new']
        group_size (`int`, *optional*, defaults to 128):
            The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
        damp_percent (`float`, *optional*, defaults to 0.1):
            The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1.
        desc_act (`bool`, *optional*, defaults to `False`):
            Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly
            speed up inference but the perplexity may become slightly worse. Also known as act-order.
        sym (`bool`, *optional*, defaults to `True`):
            Whether to use symetric quantization.
        true_sequential (`bool`, *optional*, defaults to `True`):
            Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing
            the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes
            quantization using inputs that have passed through the previously quantized layers.
        use_cuda_fp16 (`bool`, *optional*, defaults to `False`):
            Whether or not to use optimized cuda kernel for fp16 model. Need to have model in fp16.
        model_seqlen (`int`, *optional*):
            The maximum sequence length that the model can take.
        block_name_to_quantize (`str`, *optional*):
            The transformers block name to quantize.
        module_name_preceding_first_block (`List[str]`, *optional*):
            The layers that are preceding the first Transformer block.
        batch_size (`int`, *optional*, defaults to 1):
            The batch size used when processing the dataset
        pad_token_id (`int`, *optional*):
            The pad token id. Needed to prepare the dataset when `batch_size` > 1.
        disable_exllama (`bool`, *optional*, defaults to `False`):
            Whether to use exllama backend. Only works with `bits` = 4.
        max_input_length (`int`, *optional*)
            The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input
            length. It is specific to the exllama backend with act-order.
    N   皙?FTrb   )bits	tokenizerdataset
group_sizedamp_percentdesc_actsymtrue_sequentialuse_cuda_fp16model_seqlenblock_name_to_quantize!module_name_preceding_first_block
batch_sizepad_token_iddisable_exllamamax_input_lengthc                 K   st   t j| _|| _|| _|| _|| _|| _|| _|| _	|| _
|	| _|
| _|| _|| _|| _|| _|| _|| _|   d S )N)r   r   r   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rX   )r0   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   r   r   r   r   rY   b  s$    zGPTQConfig.__init__c                    s0   t | j}dddg  fdd| D }|S )Nrv   rp   rw   c                    s   i | ]\}}| kr||qS r   r   ).0ijZloading_attibutesr   r   
<dictcomp>  s       z5GPTQConfig.get_loading_attributes.<locals>.<dictcomp>)r6   r7   r8   r   )r0   Zattibutes_dictZloading_attibutes_dictr   r{   r   get_loading_attributes  s    
z!GPTQConfig.get_loading_attributesc                 C   s   | j dkrtd| j  | jdkr6| jdkr6tdd| j  k rLdk sVn td| jdk	rt| jtr| jd	krtd
| j nt| jtstd| j dS )z;
        Safety checker that arguments are correct
        )r
            z6Only support quantization to [2,3,4,8] bits but found r   z0group_size must be greater than 0 or equal to -1rb   z"damp_percent must between 0 and 1.N)Z	wikitext2Zc4zc4-newZptbzptb-newzYou have entered a string value for dataset. You can only choose between
                        ['wikitext2','c4','c4-new','ptb','ptb-new'], but we found zdataset needs to be either a list of string or a value in
                    ['wikitext2','c4','c4-new','ptb','ptb-new'], but we found )rh   rW   rk   rl   rj   rT   rC   r[   r9   r   r   r   rX     s(    


zGPTQConfig.post_init)NNrf   rg   FTTFNNNrb   NFN)r   r   r   r@   intr   r   r   r   rC   rZ   rF   rY   r}   rX   r   r   r   r   re   .  sH   5               
're   )r6   importlib.metadatar]   r-   rD   dataclassesr   enumr   typingr   r   r   r   r   	packagingr	   utilsr   r   rR   Z
get_loggerr   loggerrC   r   r   rG   re   r   r   r   r   <module>   s&   
V -