o
    h                     @   s   d dl Z d dlZd dlZd dlZd dlmZ dd ZG dd deZdd	d
Z	de
dee
e
f fddZdgddfddZdd Zdd ZdS )    N)Tuplec           	      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.   H/var/www/html/ai/venv/lib/python3.10/site-packages/bitsandbytes/utils.pyoutlier_hook   s(   

0

r0   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_hookr0   )r3   modelnmr.   r.   r/   
initialize.   s   zOutlierTracer.initializec                 C   s   t | ddS )Nr7   F)getattrr2   r.   r.   r/   is_initialized;   s   zOutlierTracer.is_initializedc                 C   s   |j   S N)datastoragedata_ptr)r3   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   )r3   r   r(   r.   r.   r/   get_outliersA   s   


zOutlierTracer.get_outliersc                 C   s   | j d u r| | | _ | j S r@   )	_instance__new__)clsr.   r.   r/   r   K   s   
zOutlierTracer.get_instance)__name__
__module____qualname__rF   r4   r=   r?   r   rE   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   rO   longmeanstdtopkr   r    )r   r   r   rU   rdmr<   mmmstdzmrT   stdmstdstdzstdvalidxr.   r.   r/   r   Q   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>j   s
    
z6execute_and_return.<locals>._decode.<locals>.<genexpr>)tuple)subprocess_err_out_tupler.   r.   r/   _decodei   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_   rh   r.   r/   &execute_and_return_decoded_std_streamso   s   zBexecute_and_return.<locals>.execute_and_return_decoded_std_streamsr.   )r_   rr   std_outstd_errr.   rq   r/   execute_and_returnh   s   	ru   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_fun_name (`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>   )	r:   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numpyra   r   loads)r   r   r   unpacked_dictr.   r.   r/   unpack_tensor_to_dict   s   


r   )r   rM   NF)r   rm   rk   r   typingr   r0   objectr   r   strru   ry   r   r   r.   r.   r.   r/   <module>   s    !
)&