
    bi                         d dl Z d dlZd dlZd dlZd Z G d d      ZddZdedeeef   fdZ		 	 	 dd	Z
d
 Zd Zd ddddZej                         D  ci c]  \  } }|| 
 c}} Zdej                   fdZyc c}} w )    Nc           
      r   t        | t        j                  j                        sJ t        j                         }|j                  | j                        }||j                  vrt        | j                        }|j                  j                  |       |j                  j                  |       t        |j                        dkD  rv|j                  d   j                         dkD  r9|j                  d   j                         | j                  j                   d   k  sJ |j                  d   |j                  |<   y |d   j#                  d|d   j                   d         }t        |dd      }t        j$                  |d         dkD  j'                  t)        t+        t        |d   j                         dz
                    }t        j,                  |dkD        d   }t        j.                  ||g      j1                         }||j                  |<   y |j2                  D ]  }|j5                           y )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hooks	            M/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/bitsandbytes/utils.pyoutlier_hookr0      s   fehhoo...'')Fv}}-FV...'6{+f%v!# r"((*Q.r*..06==3F3Fq3IIII060CF%%f- 1X]]2uQx~~b'9:F+F!ANKIIeAh'!+00T%E!HNN@SVW@W:X5Y0ZD ;;tax03L))[,$?@GGIK0;F%%f-LL 	DKKM	    c                   >    e Zd ZdZd Zd Zd Zd Zd Ze	d        Z
y)r   Nc                     t        d      )NzCall get_instance() instead)RuntimeErrorselfs    r/   __init__zOutlierTracer.__init__,   s    899r1   c                 <   d | _         d | _        g | _        g | _        i | _        d| _        g | _        |j                         D ]X  \  }}t        |t        j                  j                        s+| j                  j                  |j                  t                     Z y )NT)last_wcurrent_outlier_dimsr   r   r   initializedr$   named_modulesr   r   r   r   r   register_forward_pre_hookr0   )r6   modelnms       r/   
initializezOutlierTracer.initialize/   s    $(!"$
'') 	MDAq!UXX__-

!!!"="=l"KL	Mr1   c                     t        | dd      S )Nr;   F)getattrr5   s    r/   is_initializedzOutlierTracer.is_initialized<   s    t]E22r1   c                 R    |j                   j                         j                         S N)datastoragedata_ptr)r6   r   s     r/   r   zOutlierTracer.get_hvalue?   s    {{""$--//r1   c                     | j                         st        d       y | j                  |      }|| j                  v r| j                  |   S y )Nz$Outlier tracer is not initialized...)rD   printr   r   )r6   r   r)   s      r/   get_outlierszOutlierTracer.get_outliersB   sJ    ""$89(T,,,**622r1   c                 ^    | j                   | j                  |       | _         | j                   S rF   )	_instance__new__)clss    r/   r   zOutlierTracer.get_instanceL   s&    == KK,CM}}r1   )__name__
__module____qualname__rN   r7   rA   rD   r   rL   classmethodr    r1   r/   r   r   )   s5    I:M30  r1   r   c                    |r?t        j                  d| j                  d   |f| j                        j	                         S | j                  |      }|j                         }|j                         }||z
  |z  }|+t        j                  |j                         |d      \  }	}
|
S t        j                  ||kD        d   }
|
S )Nr   r   )sizedevice)kr
   )
r   randintr   rX   longstdmeantopkr   r!   )r   r   r   r^   rdmr\   stdmstdstdzstdvalidxs              r/   r   r   S   s    
}}QQtgfmmTYY[[
**]
#C88:DWWYF$J& D::cggi4Q7S J kk$-(+Jr1   command_stringreturnc                 2    d fd} ||       \  }}||fS )Nc                 &    t        d | D              S )Nc              3   Z   K   | ]#  }|j                  d       j                          % yw)zUTF-8N)decodestrip).0	to_decodes     r/   	<genexpr>z6execute_and_return.<locals>._decode.<locals>.<genexpr>g   s$     a9Y%%g.446as   )+)tuple)subprocess_err_out_tuples    r/   _decodez#execute_and_return.<locals>._decodef   s    aH`aaar1   c                      t        j                  t        j                  |       t         j                  t         j                        j                               S )N)stdoutstderr)
subprocessPopenshlexsplitPIPEcommunicate)re   rq   s    r/   &execute_and_return_decoded_std_streamszBexecute_and_return.<locals>.execute_and_return_decoded_std_streamsi   sA    N+!! km
 	
r1   rU   )re   r{   std_outstd_errrq   s       @r/   execute_and_returnr~   e   s*    b
 >nMGWGr1   c                 4   | j                         D ]  \  }}t        t        |j                                     dkD  rt	        |||||       t        |t        j                  j                        s`||vse| j                  |   } ||j                  |j                  |j                  du      | j                  |<   |r<|j                  | j                  |   _        |j                  | j                  |   _        |t        ||d      }| ||        | 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   rC   )	r>   linear_replacementskip_modulescopy_weightspost_processing_functionnamer&   
old_modulefuncs	            r/   r   r   v   s    . ,,. !ftFOO%&'!+6#5|\Sklfehhoo.4|3K-J#5""##4'$ENN4 
 .8.?.?t$+,6OOt$)'3v'?F#L%!& Lr1   c                     t        j                  |       }|j                  d      }t        j                  t        |      t        j                        }|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_datas       r/   pack_dict_to_tensorr      s?     zz+&H)J,,tJ/u{{CKr1   c                     t        | j                         j                               }|j                  d      }t	        j
                  |      }|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numpyrj   r   loads)r   r   r   unpacked_dicts       r/   unpack_tensor_to_dictr      sB     {(..01J  )HJJx(Mr1   r      r   )rowcol32
col_turing
col_amperetc                     | j                   j                  dk(  rt        j                  j	                          y | j                   j                  dk(  rt        j
                  j	                          y y )Ncudaxpu)rX   typer   r   synchronizer   )r   s    r/   sync_gpur      sG    xx}}

 	
%			 
 r1   )r   g      @NF))lm_headFN)r   rw   ru   r   r0   r   r   strro   r~   r   r   r   "LINEAR_8BIT_WEIGHTS_FORMAT_MAPPINGitems*INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPINGTensorr   )r   rc   s   00r/   <module>r      s       B' 'T$s uS#X ( !*Z"" ./![\%] "KmKsKsKu-vKT3c4i-v *    .ws   A8