o
    3wi                     @   s   d dl Z d dlZd dlZd dlZdd ZG dd dZddd	Zd
edeeef fddZ				dddZ
dd Zdd Zd ddddZdd e D ZdS )    Nc           	      C   sF  t | tjjs	J t }|| j}||jvrt	| j}|j
| |j| t|j
dkrR|j
d  dkrH|j
d  | jjd k sHJ |j
d |j|< d S |d d|d jd }t	|ddd}t|d dkjttt|d jd d}t|dkd }t||g }||j|< d S |jD ]}|  qd S )N   r      )reduction_dimzscore   )dim)
isinstancetorchnnLinearOutlierTracerget_instance
get_hvalueweighthvalue2outlier_idxfind_outlier_dimsoutliersappendhvalueslennumelmaxshapeviewabssumlistrangewherecatuniquehooksremove)	moduleinputtracerhvalueoutlier_idxmergeddimsoutlier_idx2hook r-   O/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/bitsandbytes/utils.pyoutlier_hook   s(   

0

r/   c                   @   sD   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Ze	dd Z
dS )r   Nc                 C   s   t d)NzCall get_instance() instead)RuntimeErrorselfr-   r-   r.   __init__,   s   zOutlierTracer.__init__c                 C   s`   d | _ d | _g | _g | _i | _d| _g | _| D ]\}}t|t	j
jr-| j|t qd S )NT)last_wcurrent_outlier_dimsr   r   r   initializedr"   named_modulesr	   r
   r   r   r   register_forward_pre_hookr/   )r2   modelnmr-   r-   r.   
initialize/   s   zOutlierTracer.initializec                 C   s   t | ddS )Nr6   F)getattrr1   r-   r-   r.   is_initialized<   s   zOutlierTracer.is_initializedc                 C   s   |j   S N)datastoragedata_ptr)r2   r   r-   r-   r.   r   ?   s   zOutlierTracer.get_hvaluec                 C   s6   |   s
td d S | |}|| jv r| j| S d S )Nz$Outlier tracer is not initialized...)r>   printr   r   )r2   r   r'   r-   r-   r.   get_outliersB   s   


zOutlierTracer.get_outliersc                 C   s   | j d u r| | | _ | j S r?   )	_instance__new__)clsr-   r-   r.   r   L   s   
zOutlierTracer.get_instance)__name__
__module____qualname__rE   r3   r<   r>   r   rD   classmethodr   r-   r-   r-   r.   r   )   s    
r         @Fc                 C   s   |rt jd| jd |f| jd S | |}| }| }|| | }| |}	|	 }
|	 }|	|
 | }|d urJt j|	 |dd\}}|S t 	||kd }|S )Nr   r   )sizedevice)kr   )
r
   randintr   rN   longmeanstdtopkr   r   )r   r   r   rT   rdmr;   mmmstdzmrS   stdmstdstdzstdvalidxr-   r-   r.   r   S   s    

r   command_stringreturnc                    s(   dd   fdd}|| \}}||fS )Nc                 S   s   t dd | D S )Nc                 s   s    | ]
}| d  V  qdS )zUTF-8N)decodestrip).0	to_decoder-   r-   r.   	<genexpr>l   s    z6execute_and_return.<locals>._decode.<locals>.<genexpr>)tuple)subprocess_err_out_tupler-   r-   r.   _decodek   s   z#execute_and_return.<locals>._decodec                    s"    t jt| t jt jd S )N)stdoutstderr)
subprocessPopenshlexsplitPIPEcommunicate)r^   rg   r-   r.   &execute_and_return_decoded_std_streamsn   s   zBexecute_and_return.<locals>.execute_and_return_decoded_std_streamsr-   )r^   rq   std_outstd_errr-   rp   r.   execute_and_returnj   s   	rt   lm_headc           	      C   s   |   D ]V\}}tt| dkrt||||| t|tjjrZ||vrZ| j	| }||j
|j|jdu| j	|< |rH|j| j	| _|j| j	| _|durZt||d}|durZ|| q| S )a  
    Replace linear modules with a new Linear module.
    Parameters:
        model (`torch.nn.Module`):
            Input model or `torch.nn.Module` as the function is run recursively.
        linear_replacement (`torch.nn.Module`):
            The linear module that replaces the old one. Only expects standard arguments.
            If other arguments need to be passed, use a lambda.
        skip_modules (`List[str]`, *optional*, defaults to `lm_head`):
            List of modules names not to convert. Defaults to `lm_head`.
        copy_weights (`bool`):
            Copy the weights from the old linear module to the new one
        post_processing_function (`str`):
            A function name of the replacement linear class that is called
            after processing.
    r   N)named_childrenr   r   childrenreplace_linearr	   r
   r   r   _modulesin_featuresout_featuresbiasr   r=   )	r9   linear_replacementskip_modulescopy_weightspost_processing_functionnamer$   
old_modulefuncr-   r-   r.   ry   {   s&   

ry   c                 C   s,   t | }|d}tjt|tjd}|S )z
    Pack a dictionary into a torch tensor for storing quant_state items in state_dict.

    Parameters:
    - source_dict: The dictionary to be packed.

    Returns:
    A torch tensor containing the packed data.
    utf-8)dtype)jsondumpsencoder
   tensorr   uint8)source_dictjson_str
json_bytestensor_datar-   r-   r.   pack_dict_to_tensor   s   


r   c                 C   s(   t |   }|d}t|}|S )z
    Unpack a torch tensor into a Python dictionary.

    Parameters:
    - tensor_data: The torch tensor containing the packed data.

    Returns:
    A Python dictionary containing the unpacked data.
    r   )bytescpunumpyr`   r   loads)r   r   r   unpacked_dictr-   r-   r.   unpack_tensor_to_dict   s   


r   r      r   )rowcol32
col_turing
col_amperec                 C   s   i | ]\}}||qS r-   r-   )rb   r   r\   r-   r-   r.   
<dictcomp>   s    r   )r   rL   NF)ru   FN)r   rl   rj   r
   r/   r   r   strre   rt   ry   r   r   "LINEAR_8BIT_WEIGHTS_FORMAT_MAPPINGitems*INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPINGr-   r-   r-   r.   <module>   s     !
*
-