
    BVh &                         d 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  ed	 e       d
      Zd Z G d d      Zy)z?Python wrapper for post training quantization with calibration.    N)	Component)convert_phase)SubComponent)Interpreter)dtypes)
LazyLoader_calibration_wrapperzKtensorflow.lite.python.optimize._pywrap_tensorflow_lite_calibration_wrapperc                 ,    t         j                  |       S )z0Adds intermediate tensors to fused op if needed.)r	   AddIntermediateTensorsmodel_contents    Z/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/lite/python/optimize/calibrator.pyadd_intermediate_tensorsr   &   s    		4	4]	CC    c                   2   e Zd ZdZ	 	 ddZd Zd Z eej                  e
j                        ej                  ej                  dddfd       Z eej                  e
j                        	 dd	       Z eej                  e
j"                        d
        Zy)
CalibratorzqCalibrates a floating point model and then quantizes it.

  This is an internal class, not a public interface.
  Nc                     |st        d      |g }|g }	 t        j                  |||      | _        || _        | j                  st        d      d| _        y# t
        $ r}t        d|z        d}~ww xY w)a  Constructor.

    Args:
      model_content: Content of a TF-Lite Flatbuffer file.
      custom_op_registerers_by_name: List of str (symbol names) that take a
        pointer to a MutableOpResolver and register custom ops.
      custom_op_registerers_by_func: List of functions that take a pointer to a
        MutableOpResolver and register custom ops.

    Raises:
      ValueError: If the calibrator was unable to open the model.
    z"`model_content` must be specified.NzFailed to parse the model: %s.zFailed to parse the model.)
ValueErrorr	   CalibrationWrapper_calibrator_model_content	Exception_interpreter)selfr   custom_op_registerers_by_namecustom_op_registerers_by_funces        r   __init__zCalibrator.__init__1   s    $ ;<<$,&(#$,&(#=-@@

'
'd
 *d 344D	  =7!;<<=s   #A 	A5"A00A5c                     g }| j                   j                  |      }t        |j                         j	                         d       }|D ]  \  }}|j                  ||           |S )Nc                     | d   d   S )N   index )items    r   <lambda>z:Calibrator._create_input_array_from_dict.<locals>.<lambda>[   s    a) r   )key)r   get_signature_runnersortedget_input_detailsitemsappend)r   signature_keyinputsinput_arraysignature_runnerinput_details
input_name_s           r   _create_input_array_from_dictz(Calibrator._create_input_array_from_dictV   sn    K((==mL**,224)M ' -
A
+,-r   c           	         i } |       D ]  }t        |t              r`t        |d   t              st        d      | j                  t        | j                        | _        |d   }| j                  ||d         }n{t        |t              r<| j                  t        | j                        | _        d}| j                  d|      }n/t        |t              rd}|}nt        dj                  |            ||vrd||<   |r}|>| j                  j                  |D cg c]  }t        |j                         c}|       nu| j                  j                  |D cg c]  }t        |j                         c}       n8|| j                  j                  |       n| j                  j                          || j                  j                  ||       | j                  j                  |        yc c}w c c}w )zFeed tensors to the calibrator.r!   zgYou need to provide either a dictionary with input names and values in the second argument in the tupleNr   r   a"  You need to provide either a dictionary with input names and values, a tuple with signature key and a dictionary with input names and values, or an array with input values in the order of input tensors of the graph in the representative_dataset function. Unsupported value from dataset: {}.T)
isinstancetupledictr   r   r   r   r3   listformatr   Prepareshape
FeedTensor)r   dataset_genresize_inputinitializedsampler,   r.   ss           r   _feed_tensorszCalibrator._feed_tensorsa   s   K- 31	FE	"&)T*  $)8K8KL$
q	886!9
 fd#$)8K8KL$
88vFfd#2
 39&.
 	
 
k	)%)M"&$$(341agg4m $$[%Id177m%IJ&$$]3$$&		"##K?##K0g31N 5 &Js   G8
G=
TFc
           
         | j                  ||       | j                  j                  t        j                  |j                               j                  t        j                  |j                               j                  |t        j                  |j                               j                  t        j                  |j                               j                  ||	      S )a  Calibrates the model with specified generator and then quantizes it.

    The input shapes of the calibrator are resized with the calibration data if
    `resize_input` is set.

    Returns:
      A quantized model.

    Args:
      dataset_gen: A generator that generates calibration samples.
      input_type: A tf.dtype representing the desired real-value input type.
      output_type: A tf.dtype representing the desired real-value output type.
      allow_float: A boolean. False if the resulting model cannot perform float
        computation, useful when targeting an integer-only backend. If False, an
        error will be thrown if an operation cannot be quantized, otherwise the
        model will fallback to float ops.
      activations_type: A tf.dtype representing the desired type for
        activations.
      bias_type: A tf.dtype representing the desired type for bias.
      resize_input: A boolean. True if the shape of the sample data is different
        from the input.
      disable_per_channel: A boolean. True if disabling per-channel
        quantization.
      disable_per_channel_quantization_for_dense_layers: A boolean. True if
        disabling per-channel quantization only in Dense layers.
    rB   r   QuantizeModelnpdtypeas_numpy_dtypenum)
r   r=   
input_typeoutput_typeallow_floatactivations_type	bias_typer>   disable_per_channel1disable_per_channel_quantization_for_dense_layerss
             r   calibrate_and_quantizez!Calibrator.calibrate_and_quantize   s    T 	{L1))
**,-11
++-.22
!002377
))+,009 r   c                    | j                  ||       | j                  j                  t        j                  |j                               j                  t        j                  |j                               j                  ||      S )a  Calibrates the model with specified generator and then quantizes it.

    Only the single op with output op_output_name will be quantized.
    The input shapes of the calibrator are resized with the calibration data.

    Returns:
      A quantized model.

    Args:
      dataset_gen: A generator that generates calibration samples.
      input_type: A tf.dtype representing the desired real-value input type.
      output_type: A tf.dtype representing the desired real-value output type.
      allow_float: A boolean. False if the resulting model cannot perform float
        computation, useful when targeting an integer-only backend. If False, an
        error will be thrown if an operation cannot be quantized, otherwise the
        model will fallback to float ops.
      op_output_name: A string, only this op will be quantized.
      resize_input: A boolean. True if the shape of the sample data is different
        from the input.
    rD   )r   r=   rJ   rK   rL   op_output_namer>   s          r   calibrate_and_quantize_singlez(Calibrator.calibrate_and_quantize_single   sj    B 	{L1))
**,-11
++-.22	 r   c                 \    | j                  |d       | j                  j                         S )zCalibrates the model with specified generator.

    Returns:
      A model with min and max calibration stats.

    Args:
      dataset_gen: A generator that generates calibration samples.
    T)r>   )rB   r   	Calibrate)r   r=   s     r   	calibratezCalibrator.calibrate   s,     	{6%%''r   )NN)T)__name__
__module____qualname____doc__r   r3   rB   r   r   OPTIMIZE_TFLITE_MODELr   #QUANTIZE_USING_DEPRECATED_QUANTIZERr   int8int32rQ   rT   	CALIBRATErW   r#   r   r   r   r   +   s     %)$(	#J	71r %%66 {{8=/	/b %%66 #	#J 00,2H2HI
( J
(r   r   )r[   numpyrF   $tensorflow.lite.python.convert_phaser   r   r   "tensorflow.lite.python.interpreterr   tensorflow.python.frameworkr   "tensorflow.python.util.lazy_loaderr   globalsr	   r   r   r#   r   r   <module>rg      sL    F  : > = : . 9
 "I	6	 D
X( X(r   