o
    b¦µi^ƒ  ã                   @   s   d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d dlmZ d dlmZ d d	lmZ d d
lmZ 	 eddgƒG dd„ dƒƒZedƒdde ¡ dfdd„ƒZedƒG dd„ deƒƒZdd„ ZG dd„ deƒZedƒ			d>dd„ƒZ	 ed ƒd?d!d"„ƒZed#ƒd$d%„ ƒZed&ƒd'd(„ ƒZed)ƒd@d*d+„ƒZed,ƒd@d-d.„ƒZG d/d0„ d0eƒZddd1dd2d3œd4d5„Zd6d7„ Z d8d9„ Z!d:d;„ Z"d<d=„ Z#dS )Aé    N)Úbackend)Úops)Úkeras_export)ÚKerasTensor)Úany_symbolic_tensors)Úcanonicalize_axis)Ústandardize_axis_for_numpy)Ú	Operation©Ú
GPTQConfigzkeras.Quantizerzkeras.quantizers.Quantizerc                   @   s2   e Zd Zddd„Zdd„ Zedd„ ƒZdd	„ Zd
S )Ú	QuantizerÚint8c                 C   s
   || _ d S ©N©Úoutput_dtype)Úselfr   © r   úS/home/ubuntu/.local/lib/python3.10/site-packages/keras/src/quantizers/quantizers.pyÚ__init__   s   
zQuantizer.__init__c                 C   s   |S )z0Compute a quantized output from an input tensor.r   )r   Úxr   r   r   Ú__call__   s   zQuantizer.__call__c                 C   s   | di |¤ŽS )a  Creates a quantizer from its config.

        This method is the reverse of `get_config`,
        capable of instantiating the same quantizer from the config
        dictionary.

        This method is used by Keras `model_to_estimator`, saving and
        loading models to HDF5 formats, Keras model cloning, some visualization
        utilities, and exporting models to and from JSON.

        Args:
            config: A Python dictionary, typically the output of get_config.

        Returns:
            A quantizer instance.
        Nr   r   )ÚclsÚconfigr   r   r   Úfrom_config   ó   zQuantizer.from_configc                 C   s   t | › dƒ‚)aÂ  Returns the config of the quantizer.

        A quantizer config is a Python dictionary (serializable)
        containing all configuration parameters of the quantizer.
        The same quantizer can be reinstantiated later
        (without any saved state) from this configuration.

        This method is optional if you are just training and executing models,
        exporting to and from SavedModels, or using weight checkpoints.

        This method is required for Keras `model_to_estimator`, saving and
        loading models to HDF5 formats, Keras model cloning, some visualization
        utilities, and exporting models to and from JSON.

        Returns:
            Python dictionary.
        z  does not implement get_config())ÚNotImplementedError©r   r   r   r   Ú
get_config.   r   zQuantizer.get_configN)r   )Ú__name__Ú
__module__Ú__qualname__r   r   Úclassmethodr   r   r   r   r   r   r      s    

r   z!keras.quantizers.abs_max_quantize©iÿÿÿé   r   Fc           	   
   C   s  |rKt  | j¡}t | ¡} t|ƒ}t |d t tj	t 
| ¡|dd|¡¡}t | |¡}t t |¡|d |d ¡}| |¡}t |¡tj||dfS t | ¡} t |d t tj	t 
| ¡|dd|¡¡}t |t  | j¡¡}t | |¡}t t |¡|d |d ¡}t ||¡}||fS )Né   T)ÚaxisÚkeepdimsr   ©Údtype)r   Ústandardize_dtyper(   r   Úconvert_to_numpyr   ÚnpÚdivideÚaddÚmaxÚabsÚmultiplyÚclipÚroundÚastypeÚconvert_to_tensorÚcast)	Úinputsr%   Úvalue_ranger(   ÚepsilonÚto_numpyÚoriginal_dtypeÚscaleÚoutputsr   r   r   Úabs_max_quantizeC   s0   	
þ
ÿ
þr=   z keras.quantizers.AbsMaxQuantizerc                   @   s0   e Zd Zde ¡ dfdd„Zdd„ Zdd„ Zd	S )
ÚAbsMaxQuantizerr"   r   c                 C   s8   t j| |d t|tƒr|f}t|ƒ| _|| _|| _d S )Nr   )r   r   Ú
isinstanceÚintÚtupler%   r7   r8   )r   r%   r7   r8   r   r   r   r   r   j   s   


zAbsMaxQuantizer.__init__c                 C   s$   t || j| j| j| jƒ\}}||fS r   )r=   r%   r7   r   r8   )r   r   Úquantized_xr;   r   r   r   r   x   s   ÿzAbsMaxQuantizer.__call__c                 C   s   | j | j| j| jdœS )N©r%   r7   r8   r   rC   r   r   r   r   r   ~   s
   üzAbsMaxQuantizer.get_configN)r   r   r    r   r8   r   r   r   r   r   r   r   r>   h   s    
ûr>   c                 C   sÆ   t  | jd¡}t | |¡} t ||¡}d|> d }|sdnd}t || ¡}t ||| ¡}t || |¡}	|t | |¡ }
t |
||¡}t |¡}t 	t ||¡|¡}t 	t ||¡|¡}||||	fS )z>Adjusts and nudges the quantization range for better accuracy.Úfloat32r$   r   )
r   Úresult_typer(   r   r5   Úsubtractr,   r1   r2   r0   )Ú	min_rangeÚ	max_rangeÚnum_bitsÚnarrow_rangeÚcompute_dtypeÚ	quant_maxÚ	quant_minÚ
diff_ranger;   Ú	inv_scaleÚzero_point_from_minÚ
zero_pointÚnudged_zero_pointÚ
nudged_minÚ
nudged_maxr   r   r   Úadjust_and_nudge‡   s   
rU   c                       s.   e Zd Zd
‡ fdd„	Zdd„ Zdd	„ Z‡  ZS )ÚFakeQuantWithMinMaxVarsé   FNc                    s    t ƒ  ¡  || _|| _|| _d S r   )Úsuperr   rI   rJ   r%   )r   rI   rJ   r%   ©Ú	__class__r   r   r   ©   s   

z FakeQuantWithMinMaxVars.__init__c                 C   s   t |||| j| j| jdS )N)rI   rJ   r%   )Úfake_quant_with_min_max_varsrI   rJ   r%   ©r   r6   Úmin_valsÚmax_valsr   r   r   Úcall¯   s   úzFakeQuantWithMinMaxVars.callc                 C   s   t |j|jdS )Nr'   )r   Úshaper(   r\   r   r   r   Úcompute_output_spec¹   s   z+FakeQuantWithMinMaxVars.compute_output_spec©rW   FN)r   r   r    r   r_   ra   Ú__classcell__r   r   rY   r   rV   ¨   s    
rV   z-keras.quantizers.fake_quant_with_min_max_varsrW   c              	      sL  t | fƒrtƒ  | ||¡S t | ¡} t |¡}t |¡}tˆƒ‰ˆ dur*tˆ | jƒ‰ t ¡ dkr•ddl	}t 
| j¡}ˆ du rd|jjt | d¡t t |d¡d¡t t |d¡d¡ˆˆd}tj||dS | jd }	t | ˆ |	¡} |jjt | d¡t |d¡t |d¡ˆˆd}tj||d}t ||	ˆ ¡S tj‡ ‡‡fd	d
„ƒ}
|
| ||ƒS )au  Perform per-tensor or per-channel fake quantization.

    `[min_vals, max_vals]` define the clamping range for the `inputs`.

    The `inputs` are quantized into the quantization range:
    - `[0, 2^num_bits - 1]` when `narrow_range=False`
    - `[1, 2^num_bits - 1]` when `narrow_range=True`

    After quantization, the values are dequantized and output as floats within
    the `[min_vals, max_vals]` interval.

    This operation supports gradient computation, allowing `min_vals` and
    `max_vals` to be trained.

    Args:
        inputs: Input Keras tensor of float dtype.
        min_vals: A global minimum scalar or a per-channel minimum tensor.
        max_vals: A global maximum scalar or a per-channel maximum tensor.
        num_bits: Quantization bit width (e.g., `8` for int8). Defaults to `8`.
        narrow_range: Whether to use narrow quantization range. Defaults to
            `False`.
        axis: Axis along which to perform per-channel quantization. If `None`,
              per-tensor quantization is performed. Defaults to `None`.


    Returns:
        Tensor: A Keras tensor with fake quantization applied.
    NÚ
tensorflowr   rD   r   )rI   rJ   r'   r$   c                    sâ   t  ˆj¡}t||ˆˆƒ\‰‰}}t t t ˆ |¡d¡¡}t ˆt 	ˆˆj¡t 	ˆˆj¡¡}t 
|ˆ¡}t t t t 
t ||¡|¡d¡¡|¡}	tj	|	|d}	t t ˆˆ¡t ˆˆ¡¡‰ d dœ‡‡ ‡‡‡fdd„
}
|	|
fS )Ng      à?r'   )Úupstreamc                    sº   | d u r|\} t  ˆ| d¡}‡ fdd„tt|jƒƒD ƒ}t  ˆˆ¡}t  || d¡}ˆ d ur5t j||d}nt  |¡}t  ˆˆ¡}t  || d¡}ˆ d urSt j||d}nt  |¡}|||fS )Nç        c                    ó   g | ]}|ˆ kr|‘qS r   r   ©Ú.0Úi©r%   r   r   Ú
<listcomp>7  ó    zqfake_quant_with_min_max_vars.<locals>._fake_quant_with_min_max_vars_per_channel.<locals>.grad.<locals>.<listcomp>rk   )r   ÚwhereÚrangeÚlenr`   Ú
less_equalÚsumÚgreater_equal)re   ÚargsÚdxÚaxesÚmin_maskÚgrad_minÚmax_maskÚgrad_max)r%   ÚmasksrT   rS   r   r   r   Úgrad1  s   


z]fake_quant_with_min_max_vars.<locals>._fake_quant_with_min_max_vars_per_channel.<locals>.grad)r   r)   r(   rU   r   Úfloorr-   r0   r1   r5   rF   Úlogical_andrs   rq   )r   Úmin_valÚmax_valr(   r;   rO   Ú
quant_zeroÚ	x_clampedÚx_clamped_shiftedÚresultr|   ©r%   rJ   rI   )r{   rT   rS   r   r   Ú)_fake_quant_with_min_max_vars_per_channel  s8   ÿÿÿÿüÿ÷ÿzOfake_quant_with_min_max_vars.<locals>._fake_quant_with_min_max_vars_per_channel)r   rV   Úsymbolic_callr   r4   r@   r   Úndimr   rd   r)   r(   Úquantizationr[   r5   ÚreshapeÚswapaxesÚ(fake_quant_with_min_max_vars_per_channelÚcustom_gradient)r6   r]   r^   rI   rJ   r%   Útfr(   r<   Ú	last_axisr†   r   r…   r   r[   ½   sH   
%ÿ



û



û?r[   z%keras.quantizers.compute_float8_scalec                 C   sR   t  |¡}t  t  || ¡d| ¡}t  | dk||¡}t  t  | ¡||¡}t  |¡S )Né   rf   )r   Ú
reciprocalr,   rn   Úisfinite)Úamaxr;   Ú	dtype_maxÚmarginÚsfr   r   r   Úcompute_float8_scaleU  s
   

r—   z,keras.quantizers.compute_float8_amax_historyc                 C   sD   t  t  t  | ¡¡|j¡}t  t j|dddggt  |dg¡¡}|S )Néÿÿÿÿ)Úshiftr   r$   )r   r5   r.   r/   r(   Úscatter_updateÚrollrŠ   )r   Úamax_historyÚamax_updateÚnew_amax_historyr   r   r   Úcompute_float8_amax_historyb  s   ýrŸ   z(keras.quantizers.quantize_and_dequantizec                 C   sh   t  tt |¡jƒ|¡}t  | t  ||¡¡}t  || |¡}t  ||¡}t  t  ||¡t  ||¡¡}|S r   )	r   r5   ÚfloatÚ	ml_dtypesÚfinfor.   r,   r1   r0   )r6   r;   Úquantized_dtyperK   Úquantized_dtype_maxr   r   r   r   Úquantize_and_dequantizem  s   ÿr¥   zkeras.quantizers.pack_int4c                    sž  |dvrt d|› dƒ‚t | j¡|kr#td|› dt | j¡› dƒ‚t| jddƒp.t| jƒ}ˆ d	k r7ˆ |7 ‰ ˆ g‡ fd
d„t|ƒD ƒ ‰‡fdd„t|ƒD ƒ}t	 
| ˆ¡}t	 |¡d	 }t	 t	 |d¡d¡}|dd…df d	 }t	j||gd	d}	|t	 |d¡ }
|	d|
…df }|ddd…df }|ddd…df }t	jd|d}t	 ||¡}t	 ||¡}t	 |t	 |d¡¡}t	 ||¡}t	 
||¡}|}|t	 |¡|fS )ae
  Pack an int4 tensor into an int8 tensor with packed nibbles.

    The input values must already be int8 in the signed range `[-8, 7]` and
    represent the desired int4 values. Packing is performed along the specified
    axis (default is 0).

    For every two consecutive rows, the **low nibble** of the output byte
    stores the value from the first row, and the **high nibble** stores
    the value from the second row.

    Args:
        arr: An `int8` or `uint8` tensor containing int4 values in the range
            `[-8, 7]`.
        axis: The axis along which to pack the tensor. Defaults to 0.
        dtype: The data type of the input and packed tensor. Can be
            `"int8"` or `"uint8"`. Defaults to `"int8"`.

    Returns:
        tuple: A tuple `(packed, packed_shape, orig_rows)` where `packed` is
            the packed int8 tensor with int4 values stored in nibbles,
            `packed_shape` is the shape of the packed tensor, and `orig_rows`
            is the original (unpacked) row count prior to any padding that may
            have been inserted when an odd number of rows is supplied.

    Example:

    ```python
    >>> import numpy as np
    >>> from keras.quantizers import pack_int4, unpack_int4

    # Example with axis=0
    # Original array has shape (3, 2)
    >>> original_array = np.array([[-3, 7], [2, -8], [1, 0]], dtype=np.int8)

    # Pack the array along axis 0. Since the length of axis 0 (3) is
    # odd, it will be padded to a length of 4. The packed array will
    # have a shape of (ceil(3/2), 2) = (2, 2).
    >>> packed, packed_shape, orig_len = pack_int4(original_array, axis=0)
    >>> print("Packed array:
", packed)
    Packed array:
    [[  45 -121]
    [   1    0]]

    # Now, unpack the array back to its original form
    >>> unpacked = unpack_int4(packed, orig_len, axis=0)
    >>> print("Unpacked array:
", unpacked)
    Unpacked array:
    [[-3  7]
    [ 2 -8]
    [ 1  0]]
    >>> np.allclose(original_array, unpacked)
    True

    # Example with axis=1
    # Original array has shape (2, 3)
    >>> original_array = np.array([[-3, 7, 2], [-8, 1, 0]], dtype=np.int8)

    # Pack along axis 1. Length of axis 1 (3) is padded to 4.
    # The new shape is (2, ceil(3/2)) = (2, 2).
    >>> packed, packed_shape, orig_len = pack_int4(original_array, axis=1)
    >>> print("Packed array:
", packed)
    Packed array:
    [[ 125   2]
    [  24   0]]

    # Unpack the array
    >>> unpacked = unpack_int4(packed, orig_len, axis=1)
    >>> print("Unpacked array:
", unpacked)
    Unpacked array:
    [[-3  7  2]
    [-8  1  0]]
    >>> np.allclose(original_array, unpacked)
    True
    ```
    ©r   Úuint8ú1Expected dtype to be 'int8' or 'uint8', but got 'ú'.z	Expected z tensor for packing, got Ú.ÚrankNr   c                    rg   r   r   rh   rk   r   r   rl   Ù  rm   zpack_int4.<locals>.<listcomp>c                    ó   g | ]}ˆ   |¡‘qS r   ©Úindexrh   ©Úpermr   r   rl   Ú  ó    r   r$   .rk   Úint32é   r'   é   )Ú
ValueErrorr   r)   r(   Ú	TypeErrorÚgetattrr`   rp   ro   r   Ú	transposeÚequalÚmodÚconcatenater5   ÚarrayÚbitwise_andÚ
bitwise_orÚ
left_shift)Úarrr%   r(   r«   Úinv_permÚ
transposedÚrowsÚ	needs_padÚzero_rowÚpadded_fullÚrows_packedÚpaddedÚlowÚhighÚmaskÚlow_uÚhigh_uÚpackedÚorig_lenr   ©r%   r°   r   Ú	pack_int4|  s@   M
ÿ
ÿÿrÑ   zkeras.quantizers.unpack_int4c                    s  |dvrt d|› dƒ‚t | j¡dvrtd| j› ƒ‚dd„ }t| jddƒp+t| jƒ}ˆ d	k r4ˆ |7 ‰ ˆ d	krŽ|d
krŽtj	d| jd}t 
| |¡}t 
t | d¡|¡}|dkr`||ƒ}||ƒ}t ||¡}	t ||¡}
tj|	|
gdd}t |dtt | ¡dd… ƒ ¡}|d|…df S ˆ g‡ fdd„t|ƒD ƒ ‰‡fdd„t|ƒD ƒ}t | ˆ¡}tj	d| jd}t 
||¡}t 
t |d¡|¡}|dkrÑ||ƒ}||ƒ}t ||¡}t ||¡}tj||gdd}t |dtt |¡dd… ƒ ¡}|d|…df }t ||¡}|S )aƒ
  Unpack a packed int4 back to an int8 tensor in the range [-8, 7].

    This function reverses the packing performed by `pack_int4`, restoring
    the original int8 tensor (values in the range [-8, 7]) from a packed int8
    tensor where each element contains two int4 values (one in the lower nibble,
    one in the upper nibble).

    The function restores the original axis order and removes any
    padding that was added during packing.

    Args:
        packed: An int8 tensor containing packed int4 values along the
            specified axis. Each int8 value encodes two int4 values.
        orig_len: The original (unpadded) length of the axis that was
            packed. This is used to remove any padding that may have
            been added during packing to ensure an even number of rows.
        axis: The axis along which the tensor was packed. Defaults to 0.
        dtype: The data type of the input and unpacked tensor. Can be
            `"int8"` or `"uint8"`. Defaults to `"int8"`.

    Returns:
        unpacked: An int8 tensor with the same shape as the original
            (unpacked) tensor, with values in the range [-8, 7].

    Example:

    ```python
    >>> import numpy as np
    >>> from keras.quantizers import pack_int4, unpack_int4

    # Example with axis=0
    # Original array has shape (3, 2)
    >>> original_array = np.array([[-3, 7], [2, -8], [1, 0]], dtype=np.int8)

    # Pack the array along axis 0. Since the length of axis 0 (3) is
    # odd, it will be padded to a length of 4. The packed array will
    # have a shape of (ceil(3/2), 2) = (2, 2).
    >>> packed, packed_shape, orig_len = pack_int4(original_array, axis=0)
    >>> print("Packed array:
", packed)
    Packed array:
    [[  45 -121]
    [   1    0]]

    # Now, unpack the array back to its original form
    >>> unpacked = unpack_int4(packed, orig_len, axis=0)
    >>> print("Unpacked array:
", unpacked)
    Unpacked array:
    [[-3  7]
    [ 2 -8]
    [ 1  0]]
    >>> np.allclose(original_array, unpacked)
    True

    # Example with axis=1
    # Original array has shape (2, 3)
    >>> original_array = np.array([[-3, 7, 2], [-8, 1, 0]], dtype=np.int8)

    # Pack along axis 1. Length of axis 1 (3) is padded to 4.
    # The new shape is (2, ceil(3/2)) = (2, 2).
    >>> packed, packed_shape, orig_len = pack_int4(original_array, axis=1)
    >>> print("Packed array:
", packed)
    Packed array:
    [[ 125   2]
    [  24   0]]

    # Unpack the array
    >>> unpacked = unpack_int4(packed, orig_len, axis=1)
    >>> print("Unpacked array:
", unpacked)
    Unpacked array:
    [[-3  7  2]
    [-8  1  0]]
    >>> np.allclose(original_array, unpacked)
    True
    ```
    r¦   r¨   r©   z1Expected int8 or uint8 tensor for unpacking, got c                 S   s:   t  | j¡}t d|¡}t d|¡}t | |k | | | ¡S )z9Converts unpacked nibbles [0, 15] to signed int4 [-8, 7].rW   é   )r   r)   r(   r   r5   rn   )r   Údtype_xÚeightÚsixteenr   r   r   Ú	to_signedV  s   zunpack_int4.<locals>.to_signedr«   Nr   r   r³   r'   r´   r   r$   rk   )r˜   .c                    rg   r   r   rh   rk   r   r   rl   w  rm   zunpack_int4.<locals>.<listcomp>c                    r¬   r   r­   rh   r¯   r   r   rl   x  r±   )rµ   r   r)   r(   r¶   r·   r`   rp   r   r¼   r½   Úright_shiftr5   ÚstackrŠ   rA   ro   r¸   )rÎ   rÏ   r%   r(   rÖ   r«   rË   Úlow_unpackedÚhigh_unpackedÚ	low_finalÚ
high_finalÚstackedÚunpackedrÁ   rÂ   rÉ   rÊ   r   rÐ   r   Úunpack_int4ÿ  sP   M
ÿ
ÿ""rß   c                       sL   e Zd ZdZeddddfdd„Zddd	„Z‡ fd
d„Zedd„ ƒZ	‡  Z
S )ÚGPTQQuantizera  A class that handles the quantization of weights using GPTQ method.

    This class provides methods to find quantization parameters (scale and zero)
    for a given tensor and can be used to quantize weights in a GPTQ context.

    Args:
        weight_bits: (int) The number of bits to quantize to (e.g., 4).
        per_channel: (bool) A flag indicating whether quantization is
            applied per-channel (`True`) or per-tensor (`False`).
            Defaults to `False`.
        symmetric: (bool) A flag indicating whether symmetric (`True`) or
            asymmetric (`False`) quantization is used. Defaults to `False`.
        group_size: (int) The size of weight groups for quantization. A
            value of -1 indicates that grouping is not used.
            Defaults to -1.
    N)Ú	tokenizerÚdatasetrD   c                 C   sF   t  | ¡ |j| _|j| _|j| _|j| _|| _d | _d | _d | _	d S r   )
r   r   Úweight_bitsÚper_channelÚ	symmetricÚ
group_sizerK   r;   ÚzeroÚmaxq)r   r   rK   r   r   r   r   ¥  s   

zGPTQQuantizer.__init__Tc              	   C   s<   t || j| j| j| j|| jd\| _| _| _| j| j| jfS )zBFinds quantization parameters (scale and zero) for a given tensor.)Úbitsrå   rä   ræ   ÚweightrK   )	Úcompute_quantization_parametersrã   rå   rä   ræ   rK   r;   rç   rè   )r   Úinput_tensorrê   r   r   r   Úfind_params¶  s   ù	zGPTQQuantizer.find_paramsc                    s*   t ƒ  ¡ }| | j| j| j| jdœ¡ |S )N)rã   rä   rå   ræ   )rX   r   Úupdaterã   rä   rå   ræ   )r   r   rY   r   r   r   Ã  s   
üÿzGPTQQuantizer.get_configc                 C   s,   t d d |d |d |d |d d}| |ƒS )Nrã   rä   rå   ræ   )rá   râ   rã   rä   rå   ræ   r
   )r   r   Úgptqr   r   r   r   Ï  s   úzGPTQQuantizer.from_config)T)r   r   r    Ú__doc__r   r   rí   r   r!   r   rc   r   r   rY   r   rà   “  s    

ý
rà   r˜   rD   )rå   rä   ræ   rê   rK   c             	   C   s^  | du rt d| › dƒ‚|r#t| jƒdk r#t d| › dt| jƒ› dƒ‚t | ¡dkr.t d	ƒ‚| j}|rM|rL|d
krBt | d
|g¡}nt | |d d
g¡}nt | dd
g¡}tj|dd}	tj|dd}
|r|t t 	|	¡|
¡}
t 
t |	d¡t |
¡|	¡}	t |	|
¡}t 
|t |	d¡|	¡}	t 
|t |
d¡|
¡}
t t t d|¡d¡|¡}t t |
|	¡|¡}|rÁt |t t |d¡d¡¡}nt t t |	¡|¡¡}t 
t |d¡d|¡}|r|rò|d
kròt |d
dg¡}t |d
dg¡}n|s|d }t t |d¡|df¡}t t |d¡|df¡}|r$t |d
dg¡}t |d
dg¡}t |d¡}|||fS )a…  
    Computes the scale and zero-point for quantization.

    This function calculates the scale and zero-point required for quantizing
    a given tensor `x` based on the specified parameters. It supports grouped,
    per-channel, per-tensor, symmetric, and asymmetric quantization - along
    with any combinations of these.

    Args:
        x: KerasTensor. The input tensor to quantize.
        bits: int. The number of bits to quantize to (e.g., 4).
        symmetric: bool. Whether to use symmetric quantization.
        per_channel: bool. Whether to quantize per channel.
        group_size: int. The group size for quantization.
        weight: bool. Whether the input tensor is a weight tensor.

    Returns:
        scale: KerasTensor. The scale tensor for quantization.
        zero: KerasTensor. The zero tensor for quantization.
        maxq: scalar. The maximum quantization value.
    NzInput tensor z cannot be None.r   zInput weight tensor z. must have a rank of at least 2, but got rank rª   r   z!Input tensor 'x' cannot be empty.r˜   r$   rk   ç:Œ0âŽyE>)r$   r$   r§   )rµ   rp   r`   r   ÚsizerŠ   Úminr.   Úmaximumr/   rn   ÚlessÚnegativer¹   rF   r-   r5   Úpowerr,   Ú	full_liker2   rq   Útile)r   ré   rå   rä   ræ   rê   rK   Úoriginal_shapeÚinput_reshapedÚ
min_valuesÚ
max_valuesÚ
zero_rangerè   r;   rç   Únum_rowsr   r   r   rë   Ü  s^   ÿÿ€ÿ
rë   c              	   C   s\   t jd|jd}t  t  |d¡||¡}t  t  t  | |¡t  ||j¡¡¡}t  |d|¡}|S )a
  Quantize a float tensor into discrete levels [0, maxq] using
    per-tensor/per-channel/grouped scaling.

    Returns `q` (same dtype as inputs/scales; float is fine) where values are in
    [0, maxq].

    Args:
        input_tensor: KerasTensor. The input tensor to quantize.
        scale: KerasTensor. The scale tensor for quantization.
        zero: KerasTensor. The zero tensor for quantization.
        maxq: KerasTensor. The maximum quantization value.

    Returns:
        KerasTensor. The quantized tensor.
    rñ   r'   r   )	r   r5   r(   rn   r¹   r2   r-   r,   r1   )rì   r;   rç   rè   r8   Ú
safe_scaleÚquantized_tensorr   r   r   Úquantize_with_zero_pointA  s   ÿÿr  c              
   C   s   t  |t  | t  ||j¡¡¡S )a`  
    Dequantizes a quantized tensor using the provided scale and zero tensors.

    Args:
        input_tensor: KerasTensor. The quantized tensor to dequantize.
        scale: KerasTensor. The scale tensor for dequantization.
        zero: KerasTensor. The zero tensor for dequantization.

    Returns:
        KerasTensor. The dequantized tensor.
    )r   r0   rF   r5   r(   )rì   r;   rç   r   r   r   Údequantize_with_zero_point^  s   ÿr  c                 C   s:   t  |d¡}t j||dd}t j||dd}t| |||ƒS )aš  Quantize the weight matrix from group params.

    This function uses the provided scale and zero tensors to quantize the
    input weights_matrix according to the group indices. It maps each column
    of the weights_matrix to its corresponding group parameters and performs
    the quantization operation.

    Args:
        weights_matrix: 2D tensor of shape [out_features, in_features].
        scale: Per-group scale tensor of shape [out_features, n_groups].
        zero: Per-group zero-point tensor of shape [out_features, n_groups].
        g_idx: Integer tensor of shape [in_features,] mapping each column to
            its group index.
        maxq: Scalar (float) representing the maximum integer quantization
            level (e.g., 2^bits - 1).

    Returns:
        A tensor with the same shape as `weights_matrix` containing the
        quantized weights produced using the provided group parameters.
    r²   r$   rk   )r   r5   Útaker  )Úweights_matrixr;   rç   Úg_idxrè   ÚgroupsÚ
scale_colsÚ	zero_colsr   r   r   Úquantize_with_sz_mapo  s   r
  c                 C   sR   t  |d¡}t j||dd}t j||dd}t  ||j¡}t  t  | |¡|¡}|S )a©  Rebuild a dequantized weight matrix from group params.

    This function uses the provided scale and zero tensors to dequantize the
    input weights_matrix according to the group indices. It maps each column
    of the weights_matrix to its corresponding group parameters and performs
    the dequantization operation.

    Args:
        weights_matrix: 2D tensor of shape [out_features, in_features].
        scale: Per-group scale tensor of shape [out_features, n_groups].
        zero: Per-group zero-point tensor of shape [out_features, n_groups].
        g_idx: Integer tensor of shape [in_features,] mapping each column to
            its group index.
        maxq: Scalar (float) representing the maximum integer quantization
            level (e.g., 2^bits - 1).

    Returns:
        A tensor with the same shape as `weights_matrix` containing the
        dequantized weights produced using the provided group parameters.
    r²   r$   rk   )r   r5   r  r(   r0   rF   )r  r;   rç   r  r  Úscales_mappedÚzeros_mappedÚ	quantizedr   r   r   Údequantize_with_sz_mapŒ  s   ÿr  rb   )r   )r   r   )$r¡   Únumpyr+   Ú	keras.srcr   r   Úkeras.src.api_exportr   Úkeras.src.backendr   r   Ú&keras.src.backend.common.backend_utilsr   r   Úkeras.src.ops.operationr	   Ú keras.src.quantizers.gptq_configr   r   r8   r=   r>   rU   rV   r[   r—   rŸ   r¥   rÑ   rß   rà   rë   r  r  r
  r  r   r   r   r   Ú<module>   sl    
1ú$!ú 


  Møe