
    eThf=                     B   S SK JrJrJr  \" 5       (       a  SSKJr  \" 5       (       a  SSKrSSKJr  SSK	Js  J
r  \R                  " \5      rSrS\R                   S\R                   4S jr\R$                  S	\R                   S
\R&                  S\R                   4S j5       r " S S\R*                  5      r " S S\R.                  R0                  5      r " S S\R.                  R0                  5      r " S S\R6                  5      r     SS jr    SS jrg)   )is_accelerate_availableis_torch_availablelogging    )init_empty_weightsN   quantized_weightsreturnc                    U R                   nUS   [        -   S-
  [        -  n[        U5      S:X  a  U4nO	U/USS Q7nU S-  n [        R                  " X0R
                  [        R                  S9nU R                  [        R                  5      n[        [        US   U-  S-   5      n[        U5       H0  nXr-  n[        X-   US   5      n	USX-
  === XXU	 SU-  -  -  sss& M2     U$ )a  
Packs a tensor of quantized weights into a compact format using 2 bits per value.

Parameters:
-----------
quantized_weights : torch.Tensor
    A tensor containing ternary quantized weights with values in {-1, 0, 1}. These values are adjusted to
    {0, 1, 2} before being packed.

Returns:
--------
torch.Tensor
    A packed tensor where each element stores 4 quantized values (each using 2 bits) in an 8-bit format.
r      Ndevicedtyper   )
shapeVALUES_PER_ITEMlentorchzerosr   uint8tominrange)
r	   original_shaperow_dimpacked_tensor_shapepackedunpackeditistartends
             X/var/www/auris/envauris/lib/python3.13/site-packages/transformers/integrations/bitnet.pypack_weightsr#      s      ',,Na ?2Q6?JG
>a&j&<);<[[,5M5MUZU`U`aF ##EKK0H	_~a0G;q@	AB2Y%/>!#45#+8##6!a%#?? 
 M    r   r   c                 t   U R                   n[        U5      S:X  a  US   [        -  nU4nOUS   [        -  nU/USS Q7n[        R                  " X@R
                  [        R                  S9n[        [        5       H%  nXbS   -  nXrS   -   nSSU-  -  n	X	-  SU-  -	  XWU& M'     UR                  U5      S-
  $ )u  
Unpacks a tensor of quantized weights that were stored in a packed format using 2 bits per value.

Parameters:
-----------
packed : torch.Tensor
    A tensor containing packed weights where each element represents 4 quantized values (using 2 bits per value).
dtype : torch.dtype
    The dtype of the returned Tensor
Returns:
--------
torch.Tensor
    A tensor of unpacked weights, where each value is converted from its packed 2-bit representation.

Example:
--------
packed = torch.tensor([[0b10100001, 0b00011000],
                       [0b10010000, 0b00001010]], dtype=torch.uint8)

# Unpack the values
unpacked = unpack_weights(packed)

# Resulting unpacked tensor
print(unpacked)
# Output: tensor([[ 0, -1],
                  [-1,  1],
                  [-1,  1],
                  [-1,  1],
                  [ 1,  0],
                  [ 0, -1],
                  [ 1, -1],
                  [ 1, -1]])

Explanation of the example:
---------------------------
Let's take the first value for example 0b10100001, we we will only focus on the first column,
because every element is unpacked across the first dimension
- First 2 bits: `01` → 0 at [0][0]
- Second 2 bits: `00` → -1 at [0][2]
- Third 2 bits: `10` → 1 at [0][4]
- Fourth 2 bits: `10` → 1 at [0][6]
the second value of the same row (0b10010000) will give the values for [0][1], [0][3], [0][5], [0][7]

We subtract 1 because during the packing process, it's easier to work with values like 0, 1, and 2. To make this possible,
we add 1 to the original ternary weights (which are typically -1, 0, and 1) when packing them. When unpacking, we reverse
this by subtracting 1 to restore the original ternary values.
r   r   Nr      r   )	r   r   r   r   r   r   r   r   r   )
r   r   packed_shapeoriginal_row_dimunpacked_shaper   r   r    r!   masks
             r"   unpack_weightsr+   9   s    b <<L
<A'?_<*,'?_<*>\!"-=>{{>--u{{SH?#O#1o%QU|%}!a%8s	 $ ;;u!!r$   c                      ^  \ rS rSr    SS\S\S\S\S\4
U 4S jjjr\R                  SS j5       r
\R                  S	 5       rS
 rSrU =r$ )	BitLinear~   in_featuresout_featuresbiasuse_rms_normrms_norm_epsc           	        > [         T	U ]  5         XPl        Xl        X l        U R                  S[        R                  " U[        -  U4[        R                  US95        U R                  S[        R                  " SUUS95        U(       a&  U R                  S[        R                  " X%US95        OS U l        S U l        U(       a  SSKJn  U" XS9U l        g g )	Nweightr   r   weight_scaler   r1   r   LlamaRMSNormeps)super__init__r   r/   r0   register_bufferr   r   r   r   onesr1   rms_normmodels.llama.modeling_llamar9   )
selfr/   r0   r1   r   r   r2   r3   r9   	__class__s
            r"   r=   BitLinear.__init__   s     	
&(KK0+>kk	
 	JJ	
   lY_)`aDI B(GDM r$   c                    SUS-
  -  * nSUS-
  -  S-
  nXAR                  5       R                  SSS9R                  R                  SS9-  nX-  R	                  5       R                  X45      nUR                  [        R                  5      U4$ )a  
Activation function : Performs symmetric, per-token quantization on the input activations.
Parameters:
-----------
x : torch.Tensor
    Input activations to be quantized.
num_bits : int, optional (default=8)
    Number of bits to use for quantization, determining the quantization range.

Returns:
--------
result : torch.Tensor
    Quantized activation tensor, with values mapped to an `int8` range.
scale : torch.Tensor
    The per-channel scaling factors used to quantize the tensor.
r   r   Tdimkeepdimh㈵>r   )absmaxvaluesclamproundr   r   int8)rB   inputnum_bitsQnQpscaleresults          r"   activation_quantBitLinear.activation_quant   s    $ X\"#8a< 1$YY[__T_:AAGGDGQQ-&&(..r6yy$e++r$   c                     XU-  -  nU$ N )rB   rR   input_scaler7   outs        r"   post_quant_processBitLinear.post_quant_process   s    \12
r$   c                    U R                   b  U R                  U5      nU R                  n[        X R                  S9nU R	                  U5      u  pE[
        R                  " UR                  U R                  5      U5      nU R                  X`R                  U5      nU R                  b-  X`R                  R                  SS5      R                  U5      -  nU$ )Nr   r   rF   )r@   r5   r+   r   rX   Flinearr   r_   r7   r1   view	expand_as)rB   rR   ww_quantinput_quantr]   ys          r"   forwardBitLinear.forward   s    ==$MM%(EKK **5#'#8#8#? HH[^^DJJ/9##A'8'8+F99 2&0033Ar$   )r1   r   r/   r0   r@   )NNFư>)   )__name__
__module____qualname____firstlineno__intboolfloatr=   r   compilerX   r_   rk   __static_attributes____classcell__rC   s   @r"   r-   r-   ~   s     ""(H(H (H 	(H (H (H (HT ]], ,. ]]  r$   r-   c                   V    \ rS rSrSr\\R                  S 5       5       r\S 5       r	Sr
g)WeightQuant   z
Implements a custom autograd function for weight quantization.
This performs ternary quantization (-1, 0, 1) based on scaling by the
mean absolute value of the weights. It uses the Straight-Through Estimator
(STE) for the backward pass.
c                    UR                   nUR                  5       nSUR                  5       R                  5       R	                  SS9-  nX-  R                  5       R                  SS5      U-  nUR                  U5      $ )Ng      ?rJ   rK   rF   r   )r   ru   rL   meanclamp_rP   rO   r   )ctxr5   r   rV   s       r"   rk   WeightQuant.forward   sp     fjjl'')00T0::.'')//A6>yyr$   c                 &    UR                  5       nU$ r[   cloner   grad_output
grad_inputs      r"   backwardWeightQuant.backward        &&(
r$   r\   Nro   rp   rq   rr   __doc__staticmethodr   rv   rk   r   rw   r\   r$   r"   r{   r{      s;     
]]      r$   r{   c                   V    \ rS rSrSr\\R                  S 5       5       r\S 5       r	Sr
g)ActQuant   a$  
Implements a custom autograd function for activation quantization.
This performs symmetric 8-bit quantization (to the range [-128, 127])
based on the maximum absolute value along the last dimension (per-token/row scaling).
It uses the Straight-Through Estimator (STE) for the backward pass.
c                    UR                   nUR                  5       nSUR                  5       R                  SSS9R                  R                  SS9-  nX-  R                  5       R                  SS5      U-  nUR                  U5      $ )N   rF   TrG   rJ   rK   i)	r   ru   rL   rM   rN   r   rP   rO   r   )r   
activationr   rV   s       r"   rk   ActQuant.forward   s       %%'
jnn&**r4*@GGNNSWNXX (//177cBUJ
}}U##r$   c                 &    UR                  5       nU$ r[   r   r   s      r"   r   ActQuant.backward   r   r$   r\   Nr   r\   r$   r"   r   r      s;     
]]$  $  r$   r   c                   `   ^  \ rS rSr      SS\S\S\S\S\S\4U 4S jjjrS	 rS
 r	Sr
U =r$ )AutoBitLineari  r/   r0   r1   online_quantr2   r3   c	           	        > [         T
U ]  XU5        X`l        S U l        U(       a  SSKJn	  U	" XS9U l        U(       dB  U R                  S[        R                  " SUUS95        U R                  U R                  5        g g )Nr   r8   r:   r7   r   r6   )r<   r=   r   r@   rA   r9   r>   r   r?   "_register_load_state_dict_pre_hook	load_hook)rB   r/   r0   r1   r   r   r   r2   r3   r9   rC   s             r"   r=   AutoBitLinear.__init__  su     	D9(B(GDM  

! 33DNNC r$   c                     US-   U;   aQ  XS-      R                   U R                  R                   :w  a(  [        XS-      U R                  R                   S9XS-   '   U$ )Nr5   rb   )r   r5   r+   )rB   
state_dictprefixargskwargss        r"   r   AutoBitLinear.load_hook"  sb     X*,X<M1N1T1TX\XcXcXiXi1i,::xFW;X`d`k`k`q`q,rJ()r$   c                 f   U R                   b  U R                  U5      nU R                  (       a   [        R                  U R                  5      nOU R                  n[
        R                  U5      n[        R                  " XU R                  5      nU R                  (       d  X0R                  -  nU$ r[   )
r@   r   r{   applyr5   r   rc   rd   r1   r7   )rB   rR   r5   outputs       r"   rk   AutoBitLinear.forward-  s~    ==$MM%(E &&t{{3F[[Fu%%3  ///Fr$   )r   r@   )TNNFFrm   )ro   rp   rq   rr   rs   rt   ru   r=   r   rk   rw   rx   ry   s   @r"   r   r     sr    
 """DD D 	D D D D D<	 r$   r   c                   ^ Tc  / mU R                  5        GH  u  pgTc  / mTR                  U5        [        U4S jU 5       5      (       Gd  [        5          [	        U[
        R                  5      (       Gal  Xa;  Gaf  UR                  nUR                  n	U(       a  UR                  S:X  a  [        UU	UR                  SLUR                  R                  UR                  R                  UR                  S:H  UR                   UR"                  S9U R$                  U'   UR                  S:X  a  U R$                  U   R'                  S5        O[)        UU	UR                  SLUR                  R                  UR                  R                  U(       a  UR                   OSU(       a  UR"                  OSS	9U R$                  U'   U R$                  U   R'                  S5        S
nSSS5        [+        [-        UR/                  5       5      5      S:  a  [1        UUTUUS9u  pTR3                  S5        GM     X4$ ! , (       d  f       N\= f)z
Private method that wraps the recursion for module replacement.

Returns the converted model and a boolean that indicates if the conversion has been successful or not.
Nc              3   J   >#    U  H  oS R                  T5      ;   v   M     g7f).N)join).0keycurrent_key_names     r"   	<genexpr>._replace_with_bitnet_linear.<locals>.<genexpr>T  s      W@V#((#344@Vs    #autobitlinearonline)r/   r0   r1   r   r   r   r2   r3   offlineFrm   )r/   r0   r1   r   r   r2   r3   Tr   )modules_to_not_convertr   quantization_confighas_been_replacedrF   )named_childrenappendanyr   
isinstancennLinearr/   r0   linear_classr   r1   r5   r   r   quantization_moder2   r3   _modulesrequires_grad_r-   r   listchildren_replace_with_bitnet_linearpop)modelr   r   r   r   pre_quantizednamemoduler/   r0   _s     `        r"   r   r   =  s    ,,.#!% W@VWWW#%fbii00T5W"("4"4K#)#6#6L*/B/O/OSb/b/<(3)5!'D!8#)==#7#7"(--"5"5*=*O*OS[*[)<)I)I)<)I)I	0t, /@@IM!NN40??F/8(3)5!'D!8#)==#7#7"(--"5"5M`)<)I)IfkM`)<)I)Ifj0t, t,;;EB(,%9 &< tFOO%&'!+#>'=!1$7"3$ A 	R ] /^ ##Q &%s   FH;;
I		c                     Uc  S/OUnU(       a(  UR                   b  UR                  UR                   5        [        [        U5      5      n[	        U UUUUS9u  pU(       d  [
        R                  S5        U $ )a)  
A helper function to replace all `torch.nn.Linear` modules by `BitLinear158` modules`.

The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.

Parameters:
    model (`torch.nn.Module`):
        Input model or `torch.nn.Module` as the function is run recursively.
    modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
        Names of the modules to not convert in `BitLinear`. In practice we keep the `lm_head` in full precision
        for numerical stability reasons.
    current_key_name (`List[`str`]`, *optional*):
        An array to track the current key of the recursion. This is used to check whether the current key (part of
        it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
        `disk`).
lm_head)r   zYou are loading your model using bitnet but no linear modules were found in your model. Please double check your model architecture, or submit an issue on github if you think this is a bug.)r   extendr   setr   loggerwarning)r   r   r   r   r   r   s         r"   replace_with_bitnet_linearr     s    2 -C,Ji[Pf2IIU%%&9&P&PQ!#&<"=>:# E 	
 Lr$   )NNNFF)NNNF)utilsr   r   r   
accelerater   r   torch.nnr   torch.nn.functional
functionalrc   
get_loggerro   r   r   Tensorr#   rv   r   r+   Moduler-   autogradFunctionr{   r   r   r   r   r   r\   r$   r"   <module>r      s   H H -##			H	% #ELL #U\\ #L A"5<< A" A" A" A"HT		 Tn%..)) .u~~&& .7BII 7x  @$J  ,r$   