o
    h)                     @   s   d dl mZmZmZ e rddlmZ e r)ddlZddlmZ ddl	m  m
Z eeZdZdejdejfdd	Zejd
ejdejdejfddZG dd dejZ					dddZ				dddZdS )   )is_accelerate_availableis_torch_availablelogging    )init_empty_weightsN   quantized_weightsreturnc           
      C   s   | j }|d t d t }t|dkr|f}n
|g|dd R }| d7 } tj|| jtjd}| tj}tt|d | d }t	|D ]#}|| }t|| |d }	|d|	|   |||	 d| > O  < qD|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end r    t/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/integrations/bitnet.pypack_weights   s   *r"   r   r   c           
      C   s   | j }t|dkr|d t }|f}n|d t }|g|dd R }tj|| jtjd}ttD ] }||d  }||d  }dd| > }	| |	@ d| ? |||< q1||d S )u5  
    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   maskr    r    r!   unpack_weights9   s   1r(   c                       sR   e Zd Zddededef fddZejddd	Zejd
d Z	dd Z
  ZS )	BitLinearNin_featuresout_featuresbiasc                    s   t    || _|| _|| _| dtj|t |ftj	|d | dtj
d||d |r;| dtj|||d d S d | _d S )Nweight)r   r   weight_scaler
   r,   )super__init__r   r*   r+   register_bufferr   r   r   r   onesr,   )selfr*   r+   r,   r   r   	__class__r    r!   r0      s.   


zBitLinear.__init__   c                 C   sb   d|d   }d|d  d }||  jdddjjdd }||  ||}|tj|fS )aX  
        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keepdimgh㈵>)r   )absmaxvaluesclamproundr   r   int8)r3   inputnum_bitsQnQpscaleresultr    r    r!   activation_quant   s
    zBitLinear.activation_quantc                 C   s   |||  }|S )Nr    )r3   r@   input_scaler.   outr    r    r!   post_quant_process   s   zBitLinear.post_quant_processc                 C   sl   | j }t|| jd}| |\}}t|| j|}| || j|}| j	d ur4|| j	
dd|7 }|S )N)r   r
   r7   )r-   r(   r   rF   Flinearr   rI   r.   r,   view	expand_as)r3   r@   ww_quantinput_quantrG   yr    r    r!   forward   s   
zBitLinear.forward)NN)r6   )__name__
__module____qualname__intboolr0   r   compilerF   rI   rR   __classcell__r    r    r4   r!   r)   ~   s    
r)   Fc              	      s   du rg  |   D ]t\}} du rg   | t fdd|D sdt 5 t|tjrU||vrU|j}|j}	t	||	|j
du|jj|jjd| j|< d}| j| d W d   n1 s_w   Y  tt| dkryt|| ||d\}
} d	 q
| |fS )
z
    Private method that wraps the recursion for module replacement.

    Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
    Nc                 3   s    | ]
}|d   v V  qdS ).N)join).0keycurrent_key_namer    r!   	<genexpr>   s    z._replace_with_bitnet_linear.<locals>.<genexpr>)r*   r+   r,   r   r   TFr   )modules_to_not_convertr_   quantization_confighas_been_replacedr7   )named_childrenappendanyr   
isinstancennLinearr*   r+   r)   r,   r-   r   r   _modulesrequires_grad_r   listchildren_replace_with_bitnet_linearpop)modelra   r_   rb   rc   pre_quantizednamemoduler*   r+   _r    r^   r!   rn      s@   

rn   c                 C   s`   |du rdgn|}|r|j dur||j  tt|}t| ||||d\} }|s.td | S )af  
    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 `EetqLinear`. 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`).
    Nlm_head)rq   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.)ra   extendrl   setrn   loggerwarning)rp   ra   r_   rb   rq   rc   r    r    r!   replace_with_bitnet_linear   s    
rz   )NNNFF)NNNF)utilsr   r   r   
accelerater   r   torch.nnrh   torch.nn.functional
functionalrJ   
get_loggerrS   rx   r   Tensorr"   rX   r   r(   Moduler)   rn   rz   r    r    r    r!   <module>   s0    
&DE
5