o
    Zh                     @   s@   d Z ddlmZmZmZ e rddlmZ 				dddZdS )	z7SpQR (Sparse-Quantized Representation) integration file   )is_accelerate_availableis_spqr_availableis_torch_available    NFc                 C   s  |du rg }t  rddlm} t rddlm} |  D ]\}}|du r&g }|| t|t	j
rd|d |vr|  d|}	|j}
|
 }|	 d|v oe|	 d|v oe|	 d	|v oe|	 d
|v }|sptd|	 d|
|	 d }|
|	 d }|
|	 d	 }|
|	 d
 }|j}|j}|j|||j|j|j||||d	| j|< d}t|| j| _| j| d W d   n1 sw   Y  n	 tt| dkrt|||||d\}}|d q| |fS )af  
    Public method that recursively replaces the Linear layers of the given model with SpQR quantized layers.
    `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
    conversion has been successful or not.

    Args:
        model (`torch.nn.Module`):
            The model to convert, can be any `torch.nn.Module` instance.
        quantization_config (`SpQRConfig`):
            The quantization config object that contains the quantization parameters.
        modules_to_not_convert (`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.
    Nr   )init_empty_weights)QuantizedLinear.z.weightz.dense_weights.shapez.row_offsets.shapez.col_vals.shapez.in_perm.shapezJThe SpQR quantization config does not contain the shape configuration for zG. This indicates that the configuration is either invalid or corrupted.)	rowscolsbitsbeta1beta2dense_weights_shaperow_offsets_shapecol_vals_shapein_perm_shapeTF)quantization_configmodules_to_not_convertcurrent_key_namehas_been_replaced)r   Z
accelerater   r   Z
spqr_quantr   Znamed_childrenappend
isinstancennZLinearjoinshapeskeys
ValueErrorin_featuresout_featuresZcreate_placehodlerr   r   r   Z_modulestypeZ
source_clsZrequires_grad_lenlistchildrenreplace_with_spqr_linearpop)modelr   r   r   r   r   r   namemoduleZtensor_namer   Zshapes_keysZshapes_validr   r   r   r   r   r   _ r*   M/var/www/auris/lib/python3.10/site-packages/transformers/integrations/spqr.pyr$      s|   

.
r$   )NNNF)__doc__utilsr   r   r   Ztorch.nnr   r$   r*   r*   r*   r+   <module>   s   