
    ij                        d dl Z 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             Z ed      dd ej(                         dfd       Z ed      dd ej(                         dfd       Zd Zd Z ed       G d de             Zd Z G d de      Z ed      	 	 	 d6d        Z	  ed!      d7d"       Z ed#      d$        Z ed%      d&        Z ed'      d8d(       Z  ed)      d8d*       Z! G d+ d,e      Z"ddd-d.d/dd0d1Z#d2 Z$d3 Z%	 d9d4Z&d9d5Z'y):    N)backend)ops)keras_export)KerasTensor)any_symbolic_tensors)canonicalize_axis)standardize_axis_for_numpy)	Operation
GPTQConfigzkeras.Quantizerzkeras.quantizers.Quantizerc                   0    e Zd ZddZd Zed        Zd Zy)	Quantizerc                     || _         y Noutput_dtype)selfr   s     t/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/quantizers/quantizers.py__init__zQuantizer.__init__   s
    (    c                     |S )z0Compute a quantized output from an input tensor. )r   xs     r   __call__zQuantizer.__call__   s    r   c                      | 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.
        r   r   )clsconfigs     r   from_configzQuantizer.from_config   s    $ }V}r   c                     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   s    r   
get_configzQuantizer.get_config0   s    $ "TF*J"KLLr   N)int8)__name__
__module____qualname__r   r   classmethodr   r!   r   r   r   r   r      s&    )  &Mr   r   z!keras.quantizers.abs_max_quantizei   r"   Fc           
      4   |rt        j                  | j                        }t        j                  |       } t        |      }t        j                  |d   t        j                  t        j                  t        j                  |       |d      |            }t        j                  | |      }t        j                  t        j                  |      |d   |d         }|j                  |      }t        j                  |      t        j                  ||      fS t        j                  |       } t        j                  |d   t        j                  t        j                  t        j                  |       |d      |            }t        j                   |t        j                  | j                              }t        j                  | |      }t        j                  t        j                  |      |d   |d         }t        j                   ||      }||fS )a  
    Quantizes the input tensor using the absolute maximum quantization scheme.

    Args:
        inputs: Input tensor to quantize.
        axis: Axis along which to compute the quantization range.
        value_range: Tuple of the minimum and maximum values of the quantization
            range.
        dtype: Data type of the quantized output.
        epsilon: Small value to avoid division by zero.
        to_numpy: Whether to perform the quantization in numpy. This performs
            the computation on the host CPU and can be useful for saving memory
            on the device. If False, the computation is performed on the device.

    Returns:
        A tuple of the quantized tensor and the scale.
       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outputss	            r   abs_max_quantizerD   E   s   4  226<<@%%f-)$/		NFF266"&&.tdCWM
 ++fe,''"((7+[^[^L..'$$W-s/D/D0
 
 	
 ""6*FJJAdTBGLE HHUG55fllCDEll65)Ghhsyy);q>;q>JGhhw&GE>r   z9keras.quantizers.abs_max_quantize_grouped_with_zero_point)i   c                 B    |rt        | ||||      S t        | ||||      S )a  Quantizes a 2D tensor using grouped asymmetric quantization with
    zero point.

    Groups are formed along axis 0 (the input/contracting dimension).
    Each group of `block_size` rows gets its own scale factor and zero point
    per column. This is useful for weight distributions that are not centered
    around zero.

    Args:
        inputs: Input tensor to quantize. Shape: `(input_dim, output_dim)`.
        block_size: Number of elements per group along axis 0.
        value_range: Tuple of `(min, max)` quantization range.
        dtype: Data type of quantized output.
        epsilon: Small value to avoid division by zero.
        to_numpy: Whether to perform computation in numpy for memory
            efficiency.

    Returns:
        A tuple `(quantized_tensor, scale, zero_point)` where:
            - `quantized_tensor`: Same shape as inputs, dtype=`dtype`.
            - `scale`: Shape `(n_groups, output_dim)` where
              `n_groups = ceil(input_dim / block_size)`.
            - `zero_point`: Shape `(n_groups, output_dim)`, dtype=`uint8`.

    Example:

    ```python
    >>> import numpy as np
    >>> from keras.quantizers import abs_max_quantize_grouped_with_zero_point
    >>> kernel = np.random.randn(512, 256).astype("float32")
    >>> quantized, scale, zero_point = abs_max_quantize_grouped_with_zero_point(
    ...     kernel, block_size=128, value_range=(-8, 7)
    ... )
    >>> quantized.shape
    (512, 256)
    >>> scale.shape  # 512 / 128 = 4 groups
    (4, 256)
    >>> zero_point.shape
    (4, 256)
    ```
    )/_abs_max_quantize_grouped_with_zero_point_numpy0_abs_max_quantize_grouped_with_zero_point_tensor)r=   
block_sizer>   r/   r?   r@   s         r   (abs_max_quantize_grouped_with_zero_pointrJ   {   s:    d >JUG
 	
 <
K r   c                    t        j                  | j                        }t        j                  |       } | j
                  \  }}t        j                  ||z        }|\  }	}
||z  }||kD  r@t        j                  ||z
  |f| j                        }t        j                  | |gd      }n| }|j                  |||      }t        j                  |dd      }t        j                  |dd      }t        j                  t        j                  ||      |z   |
|	z
        }t        j                   t        j                  | |            |	z   }t        j"                  ||	|
      }t        j                   t        j                  ||            |z   }t        j"                  ||	|
      }|j%                  |      }|j                  ||      d|ddf   }t        j&                  |d      }t        j&                  |d      j%                  d      }t        j(                  |      t        j(                  ||      t        j(                  |      fS )	zNumPy implementation of grouped asymmetric quantization.

    Uses NumPy for computation to reduce GPU memory usage during
    model quantization.
    r.   r   r,   r*   Tr+   Nr"   )r   r0   r/   r   r1   shapemathceilr2   zerosconcatenatereshapeminr5   r3   subtractr9   r8   r:   squeezer;   )r=   rI   r>   r/   r?   rA   	input_dim
output_dimn_groupsqminqmaxpadded_input_dimpaddinginputs_paddedinputs_reshapedmin_valmax_valrB   
zero_pointrC   s                       r   rG   rG      s    ..v||<N!!&)F"LLIzyyZ/0HJD$  *,)#((	):6fll
 '8qA#++Hj*MO ff_1t<Gff_1t<G IIbkk'73g=td{KE "))WHe45<JT40J hhryy%89JFGgggtT*GnnU#G oo.
;JYJMJGJJu1%EJQ/66v>J 	g&e>:j) r   c           
      ^   t        j                  | j                        }t        j                  |       } t        j
                  |       }|d   }|d   }|\  }	}
|
|	z
  dz   }t        t        j                  |            }t        t        j                  t        |      |z              }||z  }t        j                  |       }t        ||dd|||d      \  }}}t        j                  |      }t        j                  |      }|t        |      z
  }|dkD  r=t        j                  ||f| j                        }t        j                  | |gd      }n| }t        j                  ||||f      }t        j                  |d      }t        j                  |d      }t        j                   t        j"                  t        j$                  ||            |      }t        j&                  ||	|
      }t        j(                  ||      }t        j                  |||f      }|d|ddf   }|||fS )	zATensor backend implementation of grouped asymmetric quantization.r   r*   FT)bits	symmetricper_channel
group_sizecompute_dtyper?   signedr.   rL   N)r   r0   r/   r   r;   rM   intrN   log2rO   	transposecompute_quantization_parametersrP   rQ   rR   expand_dimsr4   r9   r3   r8   r<   )r=   rI   r>   r/   r?   rA   input_shaperV   rW   rY   rZ   
num_levelsrc   rX   r[   inputs_tscale_tzero_point_t_rB   ra   pad_sizer\   r]   r^   scale_expandedzero_point_expandedrC   s                               r   rH   rH      s    ..v||<N""6*F))F#KAIQJJD$ qJtyy$%D499S^j89:H*, }}V$H  ?$	 G\1 MM'"E|,J  #i.0H!|))Xz2&,,G(9Bkk*j9O
 __U3N//*1= gg		#**_n=>G hhwd+Ghhw&G kk'$4j#ABGjyj!m$GE:%%r   z keras.quantizers.AbsMaxQuantizerc                   H    e Zd Zdd ej                         dfdZddZd Zy)AbsMaxQuantizerNr'   r"   c                     t         j                  | |       |$t        |t              r|f}t	        |      | _        nd | _        || _        || _        |dk(  r|d   dk  s|d   dkD  rt        d|       y y )Nr   r"   r   ir*   r(   zuQuantizer with output_dtype='int8' requires value_range to be within the interval [-128, 127]. Received: value_range=)	r   r   
isinstanceri   tupler,   r>   r?   
ValueError)r   r,   r>   r?   r   s        r   r   zAbsMaxQuantizer.__init__5  s     	4l;$$wdDIDI&6!1~$A(< ##.-1  )= "r   c                     || j                   }|d}t        ||| j                  | j                  | j                  |      \  }}||fS )a  
        Quantizes the input tensor.

        Args:
            x: Input tensor to quantize.
            axis: Axis along which to compute the quantization range. If None,
                uses the axis specified in the constructor. If None and no axis
                was specified in the constructor, defaults to -1.
            to_numpy: Whether to perform the quantization in numpy. This
                performs the computation on the host CPU and can be useful for
                saving memory on the device. If False, the computation is
                performed on the device.

        Returns:
            A tuple of the quantized tensor and the scale.
        )r,   rD   r>   r   r?   )r   r   r,   r@   quantized_xrB   s         r   r   zAbsMaxQuantizer.__call__M  sZ    " <99D<D-LL
U E!!r   c                     | j                   | j                  | j                  d}| j                  | j                  |d<   |S )N)r>   r?   r   r,   )r>   r?   r   r,   )r   r   s     r   r!   zAbsMaxQuantizer.get_configm  s@    ++|| --

 99 !YYF6Nr   )NF)r#   r$   r%   r   r?   r   r   r!   r   r   r   rx   rx   3  s)     !0"@r   rx   c                    t        j                  | j                  d      }t        j                  | |      } t        j                  ||      }d|z  dz
  }|sdnd}t        j
                  ||       }t        j                  |||z
        }t        j                  ||z
  |      }	|t        j                  | |      z
  }
t        j                  |
||      }t        j                  |      }t        j                  t        j
                  ||      |      }t        j                  t        j
                  ||      |      }||||	fS )z>Adjusts and nudges the quantization range for better accuracy.float32r*   r   )
r   result_typer/   r   r<   rT   r3   r8   r9   r7   )	min_range	max_rangenum_bitsnarrow_rangerg   	quant_max	quant_min
diff_rangerB   	inv_scalezero_point_from_minra   nudged_zero_point
nudged_min
nudged_maxs                  r   adjust_and_nudger   x  s    ''	CMM2IM2Ih!#I%1Ii3J JJz9y#89E 

9y0*=I $cjjE&BB -y)DJ 		*- cll96GH%PJcll96GH%PJz5)33r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )FakeQuantWithMinMaxVarsc                 L    t         |           || _        || _        || _        y r   )superr   r   r   r,   )r   r   r   r,   	__class__s       r   r   z FakeQuantWithMinMaxVars.__init__  s$     (	r   c                 `    t        |||| j                  | j                  | j                        S )N)r   r   r,   )fake_quant_with_min_max_varsr   r   r,   r   r=   min_valsmax_valss       r   callzFakeQuantWithMinMaxVars.call  s/    +]]**
 	
r   c                 D    t        |j                  |j                        S )Nr.   )r   rM   r/   r   s       r   compute_output_specz+FakeQuantWithMinMaxVars.compute_output_spec  s    6<<v||<<r      FN)r#   r$   r%   r   r   r   __classcell__r   s   @r   r   r     s    
=r   r   z-keras.quantizers.fake_quant_with_min_max_varsc           
      r   t        | f      rt               j                  | ||      S t        j                  |       } t        j                  |      }t        j                  |      }t              t        | j                        t        j                         dk(  rpddl	}t        j                  | j                        }|j                  j                  t        j                  | d      t        j                  t        j                  |d      d      t        j                  t        j                  |d      d            }t        j                  ||      S | j                  dz
  }	t        j                   | |	      } |j                  j#                  t        j                  | d      t        j                  |d      t        j                  |d            }t        j                  ||      }t        j                   ||	      S t        j$                  f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   r   r   )r   r   r.   r*   c                     t        j                   j                        }t              \  }}t	        j
                  t	        j                  t	        j                   |      d            }t	        j                  t	        j                   j                              }t	        j                  |      }t	        j                  t	        j
                  t	        j                  t	        j                  t	        j                  ||      |      d            |      }	t	        j                  |	|      }	t	        j                  t	        j                         t	        j                               d d fd
}
|	|
fS )Ng      ?r.   )upstreamc                    | |\  } t        j                  
| d      }t        t        |j                              D cg c]
  }|	k7  s	| }}t        j
                        }t        j                  || d      }	t        j                  ||      }nt        j                  |      }t        j                  |t        j                              }t        j                        }t        j                  || d      }	t        j                  ||      }nt        j                  |      }t        j                  |t        j                              }|||fS c c}w )N        rL   )	r   whererangelenrM   
less_equalsumrR   greater_equal)r   argsdxiaxesmin_maskgrad_minmax_maskgrad_maxr,   masksr`   r_   r   r   r   s            r   gradz]fake_quant_with_min_max_vars.<locals>._fake_quant_with_min_max_vars_per_channel.<locals>.grad"  s!   " 5(C0B$S]3A!qDyAADA ~~a4Hyy8S9H778$7778,{{8SYYw-?@H ((J7Hyy8S9H778$7778,{{8SYYw-?@Hx))- Bs   
E
E)r   r0   r/   r   r   floorr4   r7   r8   r<   rT   logical_andr   r   )r   r_   r`   r/   rB   r   
quant_zero	x_clampedx_clamped_shiftedresultr   r   r   r   r,   r   r   s   ```        @@@r   )_fake_quant_with_min_max_vars_per_channelzOfake_quant_with_min_max_vars.<locals>._fake_quant_with_min_max_vars_per_channel   sC   ))!''2 4DWh4
0
Jy YYGGCLL*i8#>

 HHHHQ
(():z
	  LLJ?IILL%6	BJ 	 

 &. a,cnnQ
.K
 "& 	* 	*< t|r   )r   r   symbolic_callr   r;   ri   r   ndimr   r   r0   r/   quantizationr   r<   rR   swapaxes(fake_quant_with_min_max_vars_per_channelcustom_gradient)r=   r   r   r   r   r,   tfr/   rC   	last_axisr   s      ```     r   r   r     s   J VI&&(66Hh
 	
 ""6*F$$X.H$$X.H8}H v{{3 L( ))&,,7<ooBB+Xr2I>Xr2I>!) C G 88G511
 aI\\&$	:FooNN+9-9-!) O G hhwe4G<<D99? ?B 5VXxPPr   z%keras.quantizers.compute_float8_scalec                 8   t        j                  |      }t        j                  t        j                  ||       d|z        }t        j                  | dkD  ||      }t        j                  t        j                  |       ||      }t        j                  |      S )N   r   )r   
reciprocalr3   r   isfinite)amaxrB   	dtype_maxmarginsfs        r   compute_float8_scaler   H  sq     NN5!E	CJJy$/F	;B	4#:r5	)B	3<<%r5	1B>>"r   z,keras.quantizers.compute_float8_amax_historyc                    t        j                  t        j                  t        j                  |             |j                        }t        j
                  t        j                  |d      dggt        j                  |dg            }|S )Nr~   )shiftr   r*   )r   r<   r5   r6   r/   scatter_updaterollrR   )r   amax_historyamax_updatenew_amax_historys       r   compute_float8_amax_historyr   U  sg    ((3773771:.0B0BCK))R(
K!%
 r   z(keras.quantizers.quantize_and_dequantizec                    t        j                  t        t        j                  |      j
                        |      }t        j                  | t        j                  ||            }t        j                  || |      }t        j                  ||      }t        j                  t        j                  ||      t        j                  ||            }|S r   )	r   r<   float	ml_dtypesfinfor5   r3   r8   r7   )r=   rB   quantized_dtyperg   quantized_dtype_maxr   s         r   quantize_and_dequantizer   `  s     ((iooo.223] 	

6388E=9:A((*=>AO$A 	SXXa/%1OPAHr   zkeras.quantizers.pack_int4c           
      V   |dvrt        d| d      t        j                  | j                        |k7  r/t	        d| dt        j                  | j                         d      t        j                  |       }t        j                  |      }t        |j                        }|dk  r||z  }t        j                  ||d      }|j                  d   }|dz  d	k(  rJd
|j                  d	d z   }t        j                  |t        j                  ||j                        gd      }|ddd   }|d	dd   }	t        j                  d|      }
t        j                  |j                  |      |
      }t        j                  |	j                  |      |
      }t        j                   |t        j"                  |t        j                  d|                  }|j                  |      }t        j                  |d|      }t        j$                  |      }|t'        |j                        |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"   uint81Expected dtype to be 'int8' or 'uint8', but got ''.z	Expected z tensor for packing, got .r   r   r*   )r*   Nr.   rL         )r|   r   r0   r/   	TypeErrorr   r1   r2   r   rM   moveaxisrQ   rP   arraybitwise_andr:   
bitwise_or
left_shiftr;   r{   )arrr,   r/   arr_npnp_dtyperankn	pad_shapelowhighmasklow_uhigh_u	packed_nppackeds                  r   	pack_int4r   o  s   Z %%?wbI
 	
   +u4w7((34A7
 	
 !!#&FxxHv||Dax [[q)F 	QA1uz6<<++	RXXiv||<=A

 1+C!$Q$<D88D)DNN3::h/6E^^DKK148Fr}}VRXXax%@AI   *I Iq$/I""9-F5)1,,r   zkeras.quantizers.unpack_int4c           	         |dvrt        d| d      t        j                  | j                        dvrt	        d| j                         d }t        | j                  dd      xs t        | j                        }|dk  r||z  }|dk(  r|d	k(  rt        j                  d
| j                        }t        j                  | |      }t        j                  t        j                  | d      |      }|dk(  r ||      } ||      }t        j                  ||      }	t        j                  ||      }
t        j                  |	|
gd      }t        j                  |dt        t        j                  |       dd       z         }|d|df   S |gt!        |      D cg c]
  }||k7  s	| c}z   }t!        |      D cg c]  }|j#                  |       }}t        j$                  | |      }t        j                  d
| j                        }t        j                  ||      }t        j                  t        j                  |d      |      }|dk(  r ||      } ||      }t        j                  ||      }t        j                  ||      }t        j                  ||gd      }t        j                  |dt        t        j                  |      dd       z         }|d|df   }t        j$                  ||      }|S c c}w c c}w )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                     t        j                  | j                        }t        j                  d|      }t        j
                  t        j                  | |      |      S )zConverts unpacked nibbles [0, 15] to signed int4 [-8, 7].

        Uses a branchless XOR approach: (x ^ 8) - 8
        This maps: 0->0, 1->1, ..., 7->7, 8->-8, 9->-7, ..., 15->-1
        r   )r   r0   r/   r   r<   rT   bitwise_xor)r   dtype_xeights      r   	to_signedzunpack_int4.<locals>.to_signedH  sD     ++AGG4G$||COOAu5u==r   r   Nr   r   r   r.   r   r"   r*   rL   r~   .)r|   r   r0   r/   r   getattrrM   r   r   r   r   right_shiftr<   stackrR   r{   r   indexrk   )r   orig_lenr,   r/   r   r   r   low_unpackedhigh_unpacked	low_final
high_finalstackedunpackedr   perminv_perm
transposedr   r   s                      r   unpack_int4r    s   Z %%?wbI
 	
   .6GG?~N
 	
> 6<<.C#fll2CDax qyTQYyyV\\2vt4(BDIF?$\2L%m4MHH\51	XXmU3
 ))Y
3!<;;wcii6G6K0L(LM 		3'' 6d91qDyQ99D',T{3!

13H3vt,J 99T.D
//*d
+C??3??:q94@D n
((3
C88D% D iid!,G{{7EE#))J2G2K,L$LMH 		3'H}}Xx0HO3 :3s   
L)L?Lc                   T     e Zd ZdZ edd      dfdZd Z fdZed        Z	 x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datasetr   c                     t         j                  |        |j                  | _        |j                  | _        |j                  | _        |j
                  | _        || _        d | _        d | _        d | _	        y r   )
r   r   weight_bitsre   rd   rf   rg   rB   zeromaxq)r   r   rg   s      r   r   zGPTQQuantizer.__init__  sg    
 	4 !--!--)) ++* 
		r   c                     t        || j                  | j                  | j                  | j                  | j
                        \  | _        | _        | _        | j                  | j                  | j                  fS )zBFinds quantization parameters (scale and zero) for a given tensor.)rc   rd   re   rf   rg   )	rl   r  rd   re   rf   rg   rB   r  r  )r   input_tensors     r   find_paramszGPTQQuantizer.find_params  s`    +J!!nn((,,,
(
DIty zz499dii//r   c                     t         |          }|j                  | j                  | j                  | j
                  | j                  d       |S )N)r  re   rd   rf   )r   r!   updater  re   rd   rf   )r   r   r   s     r   r!   zGPTQQuantizer.get_config  sH    #%#//#//!^^"oo		
 r   c           	      L    t        d d |d   |d   |d   |d         } | |      S )Nr  re   rd   rf   )r  r  r  re   rd   rf   r   )r   r   gptqs      r   r   zGPTQQuantizer.from_config  s>    }-}-[)l+
 4yr   )r#   r$   r%   __doc__r   r   r  r!   r&   r   r   r   s   @r   r  r    s:    & D$7"
0
 	 	r   r  r~   r   r   )rd   re   rf   rg   r?   rh   c          	      	   | t        d|  d      t        | j                        dk  r%t        d|  dt        | j                         d      t        j                  |       dk(  rt        d      | j                  d   | j                  d	   }	}|r|dkD  r|	|z   d	z
  |z  }
nd	}
|
d	kD  ru|	|z  }|dk7  r#||z
  }t        j
                  | ddgd|ggd
      } t        j                  | ||
|g      }t        j                  |d      }t        j                  |d      }nN|r|dgnd	dg}t        j                  | |      }t        j                  |d	      }t        j                  |d	      }|rit        j                  t        j                  |      |      }t        j                  t        j                  |d      t        j                  |      |      }|}t        j                  ||      }t        j                  |t        j                  |d	      |      }t        j                  |t        j                   |d	      |      }t        j"                  t        j                  t        j$                  d|      d	      |      }t        j                  ||      }|dkD  rt        j                   ||      }t        j&                  ||      }t        j                  t        j(                  |d      d|      }|rd|d	z
  z   }d|d	z
  z  d	z
  }|rBt        j*                  |t        j&                  t        j                   |d	      d      |z         }nPt        j                   t        j,                  t        j&                  t        j                  |      |            |      }t        j.                  |||      }n}|r?t        j*                  |t        j&                  t        j                   |d	      d            }n<t        j,                  t        j&                  t        j                  |      |            }|
d	kD  rn|r1t        j                  |dd	g      }t        j                  |dd	g      }nXt        j0                  t        j                  |d      |d	f      }t        j0                  t        j                  |d      |d	f      }|rdnd}|t        j"                  ||      |fS )a<  
    Computes the scale and zero-point for quantizing weight tensors.

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

    For grouped quantization (per_channel=True, group_size > 0), the output
    shapes are [out_features, n_groups] where n_groups is the number of groups
    along the in_features dimension.

    Args:
        x: KerasTensor. The weight tensor to quantize with shape
            [out_features, in_features].
        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. -1 means no grouping.
        compute_dtype: str. The dtype for computation. Defaults to "float32".
        epsilon: float. Small value added to (max - min) before computing
            scale to avoid division by zero. Defaults to 0.0.
        signed: bool. Whether to use signed quantization range. If True, uses
            range [-2^(bits-1), 2^(bits-1)-1] (e.g., [-8, 7] for 4-bit).
            If False, uses range [0, 2^bits-1] (e.g., [0, 15] for 4-bit).
            Defaults to False.

    Returns:
        scale: KerasTensor. The scale tensor for quantization.
        zero: KerasTensor. The zero tensor for quantization (int8 if signed,
            uint8 if unsigned).
        maxq: scalar. The maximum quantization value.
    z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   )constant_valuesrL   r~   :0yE>)r*   r*   r"   r   )r|   r   rM   r   sizepadrR   rS   r5   maximumr6   r   lessnegativeequalrT   r4   r<   powerr3   r   	full_liker9   r8   tile)r   rc   rd   re   rf   rg   r?   rh   out_featuresin_featuresrX   	remainderrt   	x_grouped
min_values
max_valuesreduction_shape
x_reshapedmax_abs
zero_ranger  range_valuesrB   rY   qmax_signedr  
zero_dtypes                              r   rl   rl     s   X 	y=+;<==
177|a"1# &%%(\N!5
 	
 xx{a<== !
AGGAJ+L zA~*,q0Z? !|*,	>!I-HQFQM2CHAKKL(J#GH	WWYQ/
WWYQ/
 1<<,!R[[O4
WWZa0
WWZa0
 ++cggj1:>YYHHZ#S\\'%:J

 
 :z2J:s||J'BJOJ:swwz1'=zJJ 88CLL1d!3Q7GD<<
J7L{ww|W5JJ|T*EIIcnnUA.e<E tax!D1Ho)==

37743CQ(G$(NOD 77		#**S\\*%=uEFD xxdK0 ==

37743CQ(GHD99SZZZ(@%HID !|	EB7+{{4"a) UF3lA5FGxxD&1L!3DE!wJ#((4,d22r   c           	         t        j                  d|j                        }t        j                  t        j                  |d      ||      }t        j
                  t        j                  t        j                  | |      t        j                  ||j                                    }t        j                  |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   r<   r/   r   r)  r9   r4   r3   r8   )r  rB   r  r  r?   
safe_scalequantized_tensors          r   quantize_with_zero_pointr=  W  s    " hht5;;/G399UA.?JyyJJ|Z0#((42M	

 xx 0!T:r   c           
          t        j                  |t        j                  | t        j                  ||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   r7   rT   r<   r/   )r  rB   r  s      r   dequantize_with_zero_pointr?  t  s4     <<s||L#((4*EF r   c                     t        j                  |d      }t        j                  |||      }t        j                  |||      }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 position
    along group_axis of the weights_matrix to its corresponding group
    parameters and performs the quantization operation.

    Args:
        weights_matrix: Tensor to quantize.
        scale: Per-group scale tensor with n_groups along group_axis.
        zero: Per-group zero-point tensor with n_groups along group_axis.
        g_idx: 1D integer tensor of length equal to the size of
            `weights_matrix` along the dimension being quantized. Each
            element specifies which group index (0 to n_groups-1) that
            position belongs to. For example, with 128 columns and
            group_size=32, g_idx would be
            `[0,0,...,0, 1,1,...,1, 2,2,...,2, 3,3,...,3]` (32 of each).
        maxq: Scalar (float) representing the maximum integer quantization
            level (e.g., 2^bits - 1).
        group_axis: The axis in `scale` and `zero` along which to index
            using `g_idx`. This determines which dimension of the
            scale/zero tensors contains the per-group values. Default: -1
            (last axis).

    Returns:
        A tensor with the same shape as `weights_matrix` containing the
        quantized weights produced using the provided group parameters.
    int32rL   )r   r<   taker=  )	weights_matrixrB   r  g_idxr  
group_axisgroups
scale_cols	zero_colss	            r   quantize_with_sz_maprI    sK    > XXeW%F%j9JvJ7I $NJ	4PPr   c                 &   t        j                  |d      }t        j                  |||      }t        j                  |||      }t        j                  ||j                        }t        j                  t        j
                  | |      |      }|S )a4  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 position
    along group_axis of the weights_matrix to its corresponding group
    parameters and performs the dequantization operation.

    Args:
        weights_matrix: Tensor to dequantize.
        scale: Per-group scale tensor with n_groups along group_axis.
        zero: Per-group zero-point tensor with n_groups along group_axis.
        g_idx: 1D integer tensor of length equal to the size of
            `weights_matrix` along the dimension being dequantized. Each
            element specifies which group index (0 to n_groups-1) that
            position belongs to. For example, with 128 columns and
            group_size=32, g_idx would be
            `[0,0,...,0, 1,1,...,1, 2,2,...,2, 3,3,...,3]` (32 of each).
        group_axis: The axis in `scale` and `zero` along which to index
            using `g_idx`. This determines which dimension of the
            scale/zero tensors contains the per-group values. Default: -1
            (last axis).

    Returns:
        A tensor with the same shape as `weights_matrix` containing the
        dequantized weights produced using the provided group parameters.
    rA  rL   )r   r<   rB  r/   r7   rT   )	rC  rB   r  rD  rE  rF  scales_mappedzeros_mappeddequantizeds	            r   dequantize_with_sz_maprN    st    8 XXeW%FHHUF<M88D&z:L88L-*=*=>L,,^\2MK r   r   )r   )r   r"   r  )(rN   r   numpyr2   	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   r?   rD   rJ   rG   rH   rx   r   r   r   r   r   r   r   r  r  rl   r=  r?  rI  rN  r   r   r   <module>rV     s        - ) 2 D M - 7 &  ">?@.M .M A.Mb 12 
GOO2 32j IJ 
GOO7 K7t4nC&L 01Ai A 2AH4B=i =* =>
 	SQ ?SQl  56	 7	 <= > 89 : *+~- ,~-B ,-R .RjEI EX E3P:$ :<$QN%r   