
    謜i9                         d dl mZ d dlmZmZ  e       rddlZddlmZ ddlmc m	Z
  ej                  e      ZdZdej                  dej                  fdZej"                  d	ej                  d
ej$                  dej                  fd       Z G d dej(                        Z G d dej,                  j.                        Z G d dej,                  j.                        Z G d dej4                        Zddee   dz  fdZ G d d      Zy)   )should_convert_module)is_torch_availablelogging    N   quantized_weightsreturnc                    | j                   }|d   t        z   dz
  t        z  }t        |      dk(  r|f}n	|g|dd }| dz  } t        j                  || j
                  t        j                        }| j                  t        j                        }t        t        |d   |z  dz         }t        |      D ]3  }||z  }t        ||z   |d         }	|d|	|z
  xxx |||	 d|z  z  z  ccc 5 |S )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
             \/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/integrations/bitnet.pypack_weightsr"      s     ',,Na ?2Q6?JG
>a&j&<);<[[,5F5M5MUZU`U`aF ##EKK0H	_~a0G;q@	AB2Y @G%'/>!#45#+8E##6!a%#??@
 M    r   r   c                 |   | j                   }t        |      dk(  r|d   t        z  }|f}n|d   t        z  }|g|dd }t        j                  || j
                  t        j                        }t        t              D ](  }||d   z  }||d   z   }dd|z  z  }	| |	z  d|z  z	  ||| * |j                  |      dz
  S )u2  
    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 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*   7   s    b <<L
<A'?_<*,'?_<*>\!"-=>{{>&--u{{SH?# 9LO#l1o%QU|%}!a%8s	9 ;;u!!r#   c                        e Zd Z	 	 	 	 d
dededededef
 fdZej                  dd       Z	ej                  d        Z
d	 Z xZS )	BitLinearin_featuresout_featuresbiasuse_rms_normrms_norm_epsc                    t         	|           || _        || _        || _        | j                  dt        j                  |t        z  |ft        j                  |             | j                  dt        j                  d||             |r)| j                  dt        j                  |||             nd | _        d | _        |rddlm}  |||      | _        y y )	Nweightr   r   weight_scaler   r/   r   LlamaRMSNormeps)super__init__r   r-   r.   register_bufferr   r   r   r   onesr/   rms_normmodels.llama.modeling_llamar7   )
selfr-   r.   r/   r   r   r0   r1   r7   	__class__s
            r!   r;   zBitLinear.__init__}   s     	
&(KK0+>kk	
 	JJ	
   l5Y_)`aDI B(,GDM r#   c                 .   d|dz
  z   }d|dz
  z  dz
  }||j                         j                  dd      j                  j                  d      z  }||z  j	                         j                  ||      }|j                  t        j                        |fS )a\  
        Activation function : Performs symmetric, per-token quantization on the input activations.
        Parameters:
        -----------
        input : 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)r@   inputnum_bitsQnQpscaleresults          r!   activation_quantzBitLinear.activation_quant   s    $ X\"#8a< 1$UYY[__T_:AAGGDGQQ%-&&(..r26yy$e++r#   c                     |||z  z  }|S N )r@   rO   input_scaler5   outs        r!   post_quant_processzBitLinear.post_quant_process   s    {\12
r#   c                    | j                   | j                  |      }| j                  }t        || j                        }| j	                  |      \  }}t        j                  |j                  | j                        |      }| j                  || j                  |      }| j                  .|| j                  j                  dd      j                  |      z  }|S )Nr   r   rC   )r>   r3   r*   r   rU   Flinearr   r[   r5   r/   view	expand_as)r@   rO   ww_quantinput_quantrY   ys          r!   forwardzBitLinear.forward   s    ==$MM%(EKK $**5#'#8#8#? [HH[^^DJJ/9##At'8'8+F99 2&0033Ar#   )NNFư>)   )__name__
__module____qualname__intboolfloatr;   r   compilerU   r[   rf   __classcell__rA   s   @r!   r,   r,   |   s     ""(H(H (H 	(H (H (HT ]], ,. ]] r#   r,   c                   N    e Zd ZdZeej                  d               Zed        Zy)WeightQuanta  
    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                 
   |j                   }|j                         }d|j                         j                         j	                  d      z  }||z  j                         j                  dd      |z  }|j                  |      S )Ng      ?rG   rH   rC   r   )r   rn   rI   meanclamp_rM   rL   r   )ctxr3   r   rS   s       r!   rf   zWeightQuant.forward   sr     fjjl'')00T0::5.'')//A6>yyr#   c                 &    |j                         }|S rW   clonerw   grad_output
grad_inputs      r!   backwardzWeightQuant.backward        &&(
r#   N	ri   rj   rk   __doc__staticmethodr   ro   rf   r~   rX   r#   r!   rs   rs      s;     
]]      r#   rs   c                   N    e Zd ZdZeej                  d               Zed        Zy)ActQuanta8  
    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                 $   |j                   }|j                         }d|j                         j                  dd      j                  j                  d      z  }||z  j                         j                  dd      |z  }|j                  |      S )N   rC   TrD   rG   rH   i)	r   rn   rI   rJ   rK   rv   rM   rL   r   )rw   
activationr   rS   s       r!   rf   zActQuant.forward   s       %%'
jnn&**r4*@GGNNSWNXX 5(//177cBUJ
}}U##r#   c                 &    |j                         }|S rW   ry   r{   s      r!   r~   zActQuant.backward   r   r#   Nr   rX   r#   r!   r   r      s;     
]]$  $  r#   r   c                   R     e Zd Z	 	 	 	 	 	 d
dedededededef fdZd Zd	 Z xZ	S )AutoBitLinearr-   r.   r/   online_quantr0   r1   c	                     t         
|   |||       || _        d | _        |rddlm}	  |	||      | _        |sD| j                  dt        j                  d||             | j                  | j                         y y )Nr   r6   r8   r5   r   r4   )r:   r;   r   r>   r?   r7   r<   r   r=   "_register_load_state_dict_pre_hook	load_hook)r@   r-   r.   r/   r   r   r   r0   r1   r7   rA   s             r!   r;   zAutoBitLinear.__init__  s{     	lD9(B(,GDM  

! 33DNNC r#   c                     |dz   |v rV||dz      j                   | j                  j                   k7  r-t        ||dz      | j                  j                         ||dz   <   |S )Nr3   r]   )r   r3   r*   )r@   
state_dictprefixargskwargss        r!   r   zAutoBitLinear.load_hook   sh     X*,FX<M1N1T1TX\XcXcXiXi1i,::fxFW;X`d`k`k`q`q,rJv()r#   c                 R   | j                   | j                  |      }| j                  r t        j                  | j                        }n| j                  }t
        j                  |      }t        j                  ||| j                        }| j                  s|| j                  z  }|S rW   )
r>   r   rs   applyr3   r   r^   r_   r/   r5   )r@   rO   r3   outputs       r!   rf   zAutoBitLinear.forward+  s    ==$MM%(E &&t{{3F[[Fu%%3  d///Fr#   )TNNFFrg   )
ri   rj   rk   rl   rm   rn   r;   r   rf   rp   rq   s   @r!   r   r     sg    
 """DD D 	D D D D<	r#   r   modules_to_not_convertc                    d}| j                         D ]  \  }}t        ||      st        j                  d      5  t	        |t
        j                        rI|r|j                  dk(  rt        |j                  |j                  |j                  du|j                  j                  |j                  j                  |j                  dk(  |j                  |j                         }|j                  dk(  r|j#                  d       nt%        |j                  |j                  |j                  du|j                  j                  |j                  j                  |r|j                  nd|r|j                   nd	      }|j#                  d       | j'                  ||       d
}ddd        |st(        j+                  d       | S # 1 sw Y   xY w)aa  
    Public method that replaces the linear layers of the given model with bitnet quantized layers.

    Args:
        model (`torch.nn.Module`):
            The model to convert, can be any `torch.nn.Module` instance.
        modules_to_not_convert (`list[str]`, *optional*, defaults to `None`):
            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.
        quantization_config (`BitNetConfig`):
            The quantization config object that contains the quantization parameters.
    FmetaautobitlinearNonline)r-   r.   r/   r   r   r   r0   r1   offlinerg   )r-   r.   r/   r   r   r0   r1   TzYou 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.)named_modulesr   r   r   
isinstancennLinearlinear_classr   r-   r.   r/   r3   r   quantization_moder0   r1   requires_grad_r,   set_submoduleloggerwarning)modelr   quantization_confighas_been_replacedmodule_namemodule
new_modules          r!   replace_with_bitnet_linearr   ;  s    $224 )V$[2HI\\&! 	)&")),&+>+K+K+^!.$*$6$6%+%8%8#[[4%}}33$mm11&9&K&Kx&W%8%E%E%8%E%E	"J +<<	I"11%8!*$*$6$6%+%8%8#[[4%}}33$mm11I\%8%E%EbgI\%8%E%Ebf"J --e4##K<$(!7	) 	))@ 	
 LI	) 	)s   E%GG	c                       e Zd Zd Z	 	 ddeeeej                     f   dej                  j                  dz  dedz  deeej                  f   fdZy)	BitNetDeserializec                     || _         y rW   )hf_quantizer)r@   r   s     r!   r;   zBitNetDeserialize.__init__v  s
    (r#   N
input_dictr   full_layer_namer	   c                    |j                         D ]  \  }}t        |t              s|d   ||<     d}|j                  |      }ddlm}	 d}
|j                  }|O|M |	||      \  }}t        |d      r5t        |d      r)|j                  }|j                  d   }|t        z  |k(  rd}
|
r,|j                  t        j                        }t        ||	      }||iS )
Nr   r3   r   )get_module_from_nameFr.   r-   Tr]   )itemsr   listpopquantizers.quantizers_utilsr   r   hasattrr.   r   r   r   r   r   r*   )r@   r   r   r   r   keyvalue
key_weightr3   r   needs_unpackingtarget_dtyper   _expected_out
actual_outweight_uint8s                    r!   convertzBitNetDeserialize.converty  s     %**, 	+JC%&"'(
3	+ 

+F||!<,UODIFAv~.76=3Q  &22#\\!_
/<?&*O!99U[[1L#LEFF##r#   NN)ri   rj   rk   r;   dictstrr   r   Tensorr   Moduler   rX   r#   r!   r   r   u  sl    ) )-&*	$d5<<001$ xx%$ t	$ 
c5<<	 $r#   r   r   ) r   r   utilsr   r   r   torch.nnr   torch.nn.functional
functionalr^   
get_loggerri   r   r   r   r"   ro   r   r*   r   r,   autogradFunctionrs   r   r   r   r   r   r   r   rX   r#   r!   <module>r      s   ? / ##			H	% #ELL #U\\ #L A"5<< A" A" A" A"HT		 Tn%..)) .u~~&& .7BII 7t7d3i$>N 7t $  $r#   