
    g                    \   d dl mZ d dlZd dlZd dlZd dlmZ d dlmZm	Z	 d dl
Z
ddlmZmZmZmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZ dd
lmZmZmZ ddl m!Z!  G d d      Z" G d de"      Z#ejH                  dejJ                  ejL                  dddddddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ' G d de"      Z(ddZ)ejT                  dddejL                  ejL                  dddejH                  df	 	 	 	 	 ddZ+dddejL                  ddddf	 	 	 ddZ,	 	 	 	 	 	 ddZ-y)    )annotationsN)Path)AnyCallable   )CalibrationDataReaderCalibrationMethodTensorsDatacreate_calibrator)ONNXQuantizer)QDQQuantizer)MODEL_SIZE_THRESHOLDQuantFormatQuantizationMode	QuantTypeload_model_with_shape_infermodel_has_pre_process_metadata&save_and_reload_model_with_shape_infer)IntegerOpsRegistryQDQRegistryQLinearOpsRegistry)TensorQuantOverridesHelperc                  L    e Zd Zej                  ej
                  ddddddfdZy)QuantConfigNFc	                    |xs g }|xs g }|xs g }|| _         || _        || _        || _        || _        || _        || _        || _        y)a  
        This is the Base class for both Static and Dynamic Quantize Configuration
        Args:
            activation_type:
                quantization data type of activation. Please refer to
                https://onnxruntime.ai/docs/performance/quantization.html for more details on data type selection
            weight_type:
                quantization data type of weight. Please refer to
                https://onnxruntime.ai/docs/performance/quantization.html for more details on data type selection
            op_types_to_quantize:
                specify the types of operators to quantize, like ['Conv'] to quantize Conv only.
                It quantizes all supported operators by default.
            nodes_to_quantize:
                List of nodes names to quantize. When this list is not None only the nodes in this list
                are quantized.
                example:
                [
                    'Conv__224',
                    'Conv__252'
                ]
            nodes_to_exclude:
                List of nodes names to exclude. The nodes in this list will be excluded from quantization
                when it is not None.
            per_channel: quantize weights per channel
            reduce_range:
                quantize weights with 7-bits. It may improve the accuracy for some models running on non-VNNI machine,
                especially for per-channel mode
            use_external_data_format: option used for large size (>2GB) model. Set to False by default.
        N)op_types_to_quantizeper_channelreduce_rangeweight_typeactivation_typenodes_to_quantizenodes_to_excludeuse_external_data_format)	selfr    r   r   r!   r"   r   r   r#   s	            V/var/www/openai/venv/lib/python3.12/site-packages/onnxruntime/quantization/quantize.py__init__zQuantConfig.__init__!   sf    R ,1r-339r$8!&(&.!2 0(@%    )__name__
__module____qualname__r   QUInt8QInt8r&    r'   r%   r   r       s,     "((OO!!&3Ar'   r   c                       e Zd Zej                  ej                  ej                  ej                  dddddddf	 d fdZ	 xZ
S )StaticQuantConfigNFc           
     t    t         |   ||||||	|
|       || _        || _        || _        |xs i | _        y)a#  
        This is the derived class for static Quantize Configuration

        Args:
            calibration_data_reader:
                a calibration data reader. It enumerates calibration data and generates inputs for the original model.
            calibrate_method:
                Current calibration methods supported are MinMax, Entropy and Percentile.
            quant_format: QuantFormat{QOperator, QDQ}.
                QOperator format quantizes the model with quantized operators directly.
                QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
            extra_options:
                key value pair dictionary for various options in different case. Current used:
                    extra.Sigmoid.nnapi = True/False  (Default is False)
                    ActivationSymmetric = True/False: symmetrize calibration data for activations (default is False).
                    WeightSymmetric = True/False: symmetrize calibration data for weights (default is True).
                    EnableSubgraph = True/False : Default is False. If enabled, subgraph will be quantized.
                                                  Dyanmic mode currently is supported. Will support more in future.
                    ForceQuantizeNoInputCheck = True/False :
                        By default, some latent operators like maxpool, transpose, do not quantize if their input is not
                        quantized already. Setting to True to force such operator always quantize input and so generate
                        quantized output. Also the True behavior could be disabled per node using the nodes_to_exclude.
                    MatMulConstBOnly = True/False:
                        Default is False for static mode. If enabled, only MatMul with const B will be quantized.
                    AddQDQPairToWeight = True/False :
                        Default is False which quantizes floating-point weight and feeds it to solely inserted
                        DeQuantizeLinear node. If True, it remains floating-point weight and inserts both
                        QuantizeLinear/DeQuantizeLinear nodes to weight.
                    OpTypesToExcludeOutputQuantization = list of op type :
                        Default is []. If any op type is specified, it won't quantize the output of ops with this
                        specific op types.
                    DedicatedQDQPair = True/False :
                        Default is False. When inserting QDQ pair, multiple nodes can share a single QDQ pair as their
                        inputs. If True, it will create identical and dedicated QDQ pair for each node.
                    QDQOpTypePerChannelSupportToAxis = dictionary :
                        Default is {}. Set channel axis for specific op type, for example: {'MatMul': 1}, and it's
                        effective only when per channel quantization is supported and per_channel is True. If specific
                        op type supports per channel quantization but not explicitly specified with channel axis,
                        default channel axis will be used.
                    CalibTensorRangeSymmetric = True/False :
                        Default is False. If enabled, the final range of tensor during calibration will be explicitly
                        set to symmetric to central point "0".
                    CalibMovingAverage = True/False :
                        Default is False. If enabled, the moving average of the minimum and maximum values will be
                        computed when the calibration method selected is MinMax.
                    CalibMovingAverageConstant = float :
                        Default is 0.01. Constant smoothing factor to use when computing the moving average of the
                        minimum and maximum values. Effective only when the calibration method selected is MinMax and
                        when CalibMovingAverage is set to True.
                    QuantizeBias = True/False :
                        Default is True which quantizes floating-point biases and it solely inserts
                        a DeQuantizeLinear node. If False, it remains floating-point bias and does not insert
                        any quantization nodes associated with biases.
                        This extra option is only effective when quant_format is QuantFormat.QDQ.
                    SmoothQuant = True/False :
                        Default is False. If enabled, SmoothQuant algorithm will be applied before quantization to do
                        fake input channel quantization.
                    SmoothQuantAlpha = float :
                        Default is 0.5. It only works if SmoothQuant is True. It controls the difficulty of weight
                        and activation quantization. A larger alpha value could be used on models with more significant
                        activation outliers to migrate more quantization difficulty to weights.
                    SmoothQuantFolding = True/False :
                        Default is True. It only works if SmoothQuant is True. If enabled, inserted Mul ops during
                        SmoothQuant will be folded into the previous op if the previous op is foldable.
                    UseQDQContribOps = True/False :
                        Default is False. If enabled, the inserted QuantizeLinear and DequantizeLinear ops will have the
                        `com.microsoft` domain, which forces use of ONNX Runtime's QuantizeLinear and DequantizeLinear
                        contrib op implementations. The contrib op implementations may support features not standardized
                        into the ONNX specification (e.g., 16-bit quantization types).
                    MinimumRealRange = float|None :
                        Default is None. If set to a floating-point value, the calculation of the quantization parameters
                        (i.e., scale and zero point) will enforce a minimum range between rmin and rmax. If (rmax-rmin)
                        is less than the specified minimum range, rmax will be set to rmin + MinimumRealRange. This is
                        necessary for EPs like QNN that require a minimum floating-point range when determining
                        quantization parameters.
                    TensorQuantOverrides = dictionary :
                        Default is {}. Set tensor quantization overrides. The key is a tensor name and the value is a
                        list of dictionaries. For per-tensor quantization, the list contains a single dictionary. For
                        per-channel quantization, the list contains a dictionary for each channel in the tensor.
                        Each dictionary contains optional overrides with the following keys and values.
                            'quant_type' = QuantType : The tensor's quantization data type.
                            'scale' =  Float         : The scale value to use. Must also specify `zero_point` if set.
                            'zero_point' = Int       : The zero-point value to use. Must also specify `scale` is set.
                            'symmetric' = Bool       : If the tensor should use symmetric quantization. Invalid if also
                                                       set `scale` or `zero_point`.
                            'reduce_range' = Bool    : If the quantization range should be reduced. Invalid if also
                                                       set `scale` or `zero_point`.
                            'rmax' = Float           : Override the maximum real tensor value in calibration data.
                                                       Invalid if also set `scale` or `zero_point`.
                            'rmin' = Float           : Override the minimum real tensor value in calibration data.
                                                       Invalid if also set `scale` or `zero_point`.
                    QDQKeepRemovableActivations = True/False:
                        Default is False. If true, "removable" activations (e.g., Clip or Relu) will not be removed, and
                        will be explicitly represented in the QDQ model. If false, these activations are automatically
                        removed if activations are asymmetrically quantized. Keeping these activations is necessary if
                        optimizations or EP transformations will later remove QuantizeLinear/DequantizeLinear
                        operators from the model.
                    QDQDisableWeightAdjustForInt32Bias = True/False:
                        Default is False. If true, QDQ quantizer will not adjust the weight's scale when the bias
                        has a scale (input_scale * weight_scale) that is too small.
            execution_provider : A enum indicates the Execution Provider such as: CPU, TRT, NNAPI, SNE, etc.
        Raises:
            ValueError: Raise ValueError if execution provider is unknown
        )r    r   r   r!   r"   r   r   r#   N)superr&   calibration_data_readercalibrate_methodquant_formatextra_options)r$   r2   r3   r4   r    r   r   r!   r"   r   r   r#   r5   	__class__s                r%   r&   zStaticQuantConfig.__init__X   sW    p 	+#!5/-#%%= 	 		
 (?$ 0(*0br'   )r2   r   )r(   r)   r*   r	   MinMaxr   QDQr   r,   r&   __classcell__r6   s   @r%   r/   r/   W   sM     +11 __!OO!!&E1!6E1 E1r'   r/   Fc                J    t         j                  t         j                  h}t         j                  t         j                  h}h d}t        | t        j                        r| nt        j                  | d      }t               }d}t        |rt        j                  |      ni       }|j                  j                  D ]$  }t        j                  j!                  |      s#d}& g }|!t        |t"              r|j%                  |       |j                  j&                  D ]Q  }|j)                  |j*                         |!t-        |      s- |||      s7|j/                  |j0                         S ||
||d|j3                         d}|r>g d}|D ci c]  \  }}||v s||j5                  |       }}}|j7                  |       t9        d |j:                  D              }|j<                  dk  rB|j?                  |       tA         fd	|jC                         D              }| v s| v s|rd|d
<   |r|j7                  |       tE        ||tF        jH                  ||t#        |jK                  |            |||	|xs |jM                         tN        k\  |      S c c}}w )a   
    Returns a configuration suitable that quantizes the entire model to integer precision.

    Params:
        model_input: Path to the input model file or ModelProto.
        calibration_data_reader: Calibration data reader.
        calibrate_methode: The calibration method. Defaults to MinMax.
        activation_type: The default activation quantization type. Defaults to QUInt8.
        weight_type: The default weight quantization type. Defaults to QInt8.
        activation_symmetric: True if activations should be quantized symmetrically (i.e, rmax == -rmin) by default.
            Defaults to false. For int8 and int16, this results in zero-point values of 0. For uint8 and uint16,
            the zero-point values are 127 and 32,767, respectively.
        weight_symmetric: True if weights should be quantized symmetrically (i.e., rmax == -rmin) by default.
            Defaults to None. If set to None, weight_symmetric is assumed true if a weight's quant type is a signed int.
        per_channel: Global option that determines if a fixed set of operator types should be quantized per-channel.
            Defaults to false. Alternatively, use the tensor-level `tensor_quant_overrides` to select individual operators
            and their quantization axes.
        reduce_range: quantize weights with 1 less bit of precision (e.g., 7 bits for QInt8). Defaults to false.
            May improve the accuracy for some models running on non-VNNI machine, especially for per-channel mode.
        keep_removable_activations: Defaults to false. If true, "removable" activations (e.g., Clip or Relu) will not
                        be removed, and will be explicitly represented in the QDQ model. If false, these activations
                        are automatically removed if activations are asymmetrically quantized. Keeping these activations
                        is necessary if optimizations or EP transformations will later remove
                        QuantizeLinear/DequantizeLinear operators from the model.
        min_real_range: Default is None. If set to a floating-point value, the calculation of the quantization parameters
            (i.e., scale and zero point) will enforce a minimum range between rmin and rmax. If (rmax - rmin)
            is less than the specified minimum range, rmax will be set to rmin + min_real_range.
        tensor_quant_overrides: tensor-level quantization overrides. Defaults to None.
            The key is a tensor name and the value is a list of dictionaries. For per-tensor quantization, the list
            contains a single dictionary. For per-channel quantization, the list contains either a dictionary for
            each channel in the tensor or a single dictionary that is assumed to apply to all channels. An 'axis'
            key must be present in the first dictionary for per-channel quantization.

            Each dictionary contains optional overrides with the following keys and values.
                'quant_type' = QuantType : The tensor's quantization data type.
                'axis' = Int             : The per-channel axis. Must be present for per-channel weights.
                'scale' =  Float         : The scale value to use. Must also specify `zero_point` if set.
                'zero_point' = Int       : The zero-point value to use. Must also specify `scale` is set.
                'symmetric' = Bool       : If the tensor should use symmetric quantization. Invalid if also
                                            set `scale` or `zero_point`.
                'reduce_range' = Bool    : If the quantization range should be reduced. Invalid if also
                                            set `scale` or `zero_point`. Only valid for initializers.
                'rmax' = Float           : Override the maximum real tensor value in calibration data.
                                            Invalid if also set `scale` or `zero_point`.
                'rmin' = Float           : Override the minimum real tensor value in calibration data.
                                            Invalid if also set `scale` or `zero_point`.
                'convert' = Dict         : A nested dictionary with the same keys for an activation
                                           tensor that should be converted to another quantization type.
                'convert["recv_nodes"] = Set : Set of node names that consume the converted activation,
                                               other nodes get the original type. If not specified,
                                               assume all consumer nodes get the converted type.
        nodes_to_exclude: List of nodes names to exclude from quantization. Alternatively, can provide a function that
            accepts an onnx.ModelProto and onnx.NodeProto as arguments and returns true if the give onnx.NodeProto
            should be excluded from quantization.
        extra_options: Additional options specified as string key/value pairs. Refer to the documentation for
            `quantize_static` for valid keys and values.

    Returns:
        A StaticQuantConfig object
    >   CastQuantizeLinearDequantizeLinearF)load_external_dataT)MinimumRealRangeQDQKeepRemovableActivationsActivationSymmetricWeightSymmetricForceQuantizeNoInputCheckTensorQuantOverrides))	symmetricCalibTensorRangeSymmetric)moving_averageCalibMovingAverage)averaging_constantCalibMovingAverageConstant)max_intermediate_outputsCalibMaxIntermediateOutputs)
percentileCalibPercentilec              3  ^   K   | ]%  }|j                   d k(  s|j                   dk(  s"| ' yw) zai.onnxN)domain).0xs     r%   	<genexpr>z!get_qdq_config.<locals>.<genexpr>g  s)     _!3Aqxx2~U^I^a!3s   #--   c              3  &   K   | ]  }|v  
 y wNr-   )rS   topset21_typess     r%   rU   z!get_qdq_config.<locals>.<genexpr>j  s     *jGi!1+=Gis   UseQDQContribOps)
r3   r4   r    r   r   r"   r   r   r#   r5   )(r   QInt16QUInt16QInt4QUInt4
isinstanceonnx
ModelProto
load_modelsetr   copydeepcopygraphinitializerexternal_data_helperuses_external_datalistextendnodeaddop_typecallableappendnameget_dictgetupdatenextopset_importversionunionanyget_quant_typesr/   r   r8   
differenceByteSizer   )!model_inputr2   r3   calibrate_argsr    r   activation_symmetricweight_symmetricr   r   keep_removable_activationsmin_real_rangetensor_quant_overridesr"   r5   	q16_typesq4_typesop_types_to_excludemodelop_typesmodel_has_external_dataoverrides_helperrh   final_nodes_to_excluderm   final_extra_optionscalib_extra_options_keysrr   keycalib_extra_options
onnx_opsetoverrides_have_opset21_typesrZ   s!                                   @r%   get_qdq_configr      s   Z !!9#4#45I!1!12HH k4??3 	__[UC 
 uH#11G,-R
 {{..$$77D&*# /  #
3CT(J%%&67   T\\"'H5E,Ft,&--dii8	 ! +'A3+%) 0 9 9 ; $
  >V
=UktSY]aoYoC##D))=U 	 
 	""#67 _!3!3__JB!1'**jGWGgGgGi*j'j$m+{m/KOk6: 23 ""=1) __'!("5"56I"JK/!"9"eU^^=MQe=e) %
s   J"Jc                  D     e Zd Zej                  dddddddf fd	Z xZS )DynamicQuantConfigNFc	           	     H    t         	|   |||||||       |xs i | _        y)a  
        This is a class for dynamic Quant Configuration

        Args:
            extra_options: key value pair dictionary for various options in different case. Current used:
                extra.Sigmoid.nnapi = True/False  (Default is False)
                ActivationSymmetric = True/False: symmetrize calibration data for activations (default is False).
                WeightSymmetric = True/False: symmetrize calibration data for weights (default is True).
                EnableSubgraph = True/False :
                    Default is False. If enabled, subgraph will be quantized. Dynamic mode currently is supported. Will
                    support more in the future.
                ForceQuantizeNoInputCheck = True/False :
                    By default, some latent operators like maxpool, transpose, do not quantize if their input is not
                    quantized already. Setting to True to force such operator always quantize input and so generate
                    quantized output. Also the True behavior could be disabled per node using the nodes_to_exclude.
                MatMulConstBOnly = True/False:
                    Default is True for dynamic mode. If enabled, only MatMul with const B will be quantized.
            execution_provider : A enum indicates the Execution Provider such as: CPU, TRT, NNAPI, SNE, etc.

        Raises:
            ValueError: Raise ValueError if execution provider is unknown
        )r   r   r   r   r!   r"   r#   N)r1   r&   r5   )
r$   r   r   r!   r"   r   r   r#   r5   r6   s
            r%   r&   zDynamicQuantConfig.__init__  s<    B 	!5#%#/-%= 	 	
 +0br'   )r(   r)   r*   r   r,   r&   r9   r:   s   @r%   r   r     s+     OO!!&*1 *1r'   r   c                h   |t         j                  k(  r|t         j                  k(  rt        d      |t         j                  k7  r"|t         j                  k(  rt        d| d      |t         j                  k(  r"|t         j                  k7  rt        d| d      t         j
                  t         j                  g}||v s||v r| t        j                  k7  rt        d      |t         j                  k(  r>|t         j                  k(  r*| t        j                  k7  rt        j                  d       y y y y )NzrONNXRuntime quantization doesn't support data format:activation_type=QuantType.QInt8, weight_type=QuantType.QUInt8zFONNXRuntime quantization doesn't support data format: activation_type=z@ !=QuantType.QFLOAT8E4M3FN, weight_type=QuantType.QFLOAT8E4M3FN.zkONNXRuntime quantization doesn't support data format: activation_type=QuantType.QFLOAT8E4M3FN, weight_type=z!=QuantType.QFLOAT8E4M3FNz8Only QuantFormat.QDQ supports 16-bit quantization types.zvPlease use QuantFormat.QDQ for activation type QInt8 and weight type QInt8. Or it will lead to bad performance on x64.)r   r,   r+   
ValueErrorQFLOAT8E4M3FNr\   r]   r   r8   loggingwarning)r4   r    r   r   s       r%   check_static_quant_argumentsr     s0   )//)kY=M=M.ML
 	
 )111kYE\E\6\TUdTe fN O
 	

 )111kYE\E\6\&-'@B
 	

 !!9#4#45I9$y(@lVaVeVeFeSTT)//)kY__.LQ]alapapQp9	
 Rq.L)r'   c                x
  ) |t         j                  k(  s|t         j                  k(  r|t        j                  k7  rt	        d      |xs i }|
xs g }
|	xs g }	|xs g }t
        j                  }|rt        |      dk(  rQt        t        j                               }t        t        j                               }t        t        ||z               }t        | t        j                        rt!        |       nt#        t%        |             }t'        |      }|st)        j*                  d       g d}|D ci c]  \  }}||v s||j-                  |       }}}|j-                  dd      rZddl}	 |j1                  d       ddl)ddlm} )fd}|j>                  j@                  D cg c]  }|jB                   }} |       } || ||      }~|jE                  |j-                  dd      |j-                  dd            }tG        jH                  d      }t%        |jB                        jK                  d      jM                         } |jO                  |        |
jQ                  |jR                  j>                  j@                  D cg c]  }|jB                  |vs|jB                   c}       t#        t%        |             }tG        jH                  d      5 } t        | t        j                        r1tU        t%        |       dz        }!t        jV                  | |!d       |!} tY        t%        |       |t%        |       jK                  d      jM                         |||      }"|j-                  dd      }#|#rat              }$|$|#z  dk7  rt	        d|$ d|# d      t[        d|$|#      D ]+  }%|%|#z   }&j]                  |%|&       |"j_                         - n|"j_                         |"ja                         }'t        |'tb              s$te        dtg        |'       dtg        |"       d	      ~"ddd       ti        |||       |tj        jl                  u rto        ||||d||'|	|
||      }(ntq        |||||'|	|
||
      }(|(js                          |(jR                  ju                  ||       |st)        j*                  d       |j-                  dd      rjw                          yyc c}}w # t2        $ r)}t)        j4                  | d	       t7        d
      |d}~ww xY wc c}w c c}w # 1 sw Y   xY w) a)  
    Given an onnx model and calibration data reader, create a quantized onnx model and save it into a file
    It is recommended to use QuantFormat.QDQ format from 1.11 with activation_type = QuantType.QInt8 and weight_type
    = QuantType.QInt8. If model is targeted to GPU/TRT, symmetric activation and weight are required. If model is
    targeted to CPU, asymmetric activation and symmetric weight are recommended for balance of performance and
    accuracy.

    Args:

        model_input: file path of model or ModelProto to quantize
        model_output: file path of quantized model
        calibration_data_reader: a calibration data reader. It
            enumerates calibration data and generates inputs for the
            original model.
        quant_format: QuantFormat{QOperator, QDQ}.
            QOperator format quantizes the model with quantized operators directly.
            QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
        activation_type:
            quantization data type of activation. Please refer to
            https://onnxruntime.ai/docs/performance/quantization.html for more details on data type selection
        calibrate_method:
            Current calibration methods supported are MinMax and Entropy.
                Please use CalibrationMethod.MinMax or CalibrationMethod.Entropy as options.
        op_types_to_quantize:
                specify the types of operators to quantize, like ['Conv'] to quantize Conv only.
                It quantizes all supported operators by default.
        per_channel: quantize weights per channel
        reduce_range:
            quantize weights with 7-bits. It may improve the accuracy for some models running on non-VNNI machine,
            especially for per-channel mode
        weight_type:
            quantization data type of weight. Please refer to
            https://onnxruntime.ai/docs/performance/quantization.html for more details on data type selection
        nodes_to_quantize:
            List of nodes names to quantize. When this list is not None only the nodes in this list
            are quantized.
            example:
            [
                'Conv__224',
                'Conv__252'
            ]
        nodes_to_exclude:
            List of nodes names to exclude. The nodes in this list will be excluded from quantization
            when it is not None.
        use_external_data_format: option used for large size (>2GB) model. Set to False by default.
        extra_options:
            key value pair dictionary for various options in different case. Current used:
                extra.Sigmoid.nnapi = True/False  (Default is False)
                ActivationSymmetric = True/False: symmetrize calibration data for activations (default is False).
                WeightSymmetric = True/False: symmetrize calibration data for weights (default is True).
                EnableSubgraph = True/False : Default is False. If enabled, subgraph will be quantized.
                                              Dyanmic mode currently is supported. Will support more in the future.
                ForceQuantizeNoInputCheck = True/False :
                    By default, some latent operators like maxpool, transpose, do not quantize if their input is not
                    quantized already. Setting to True to force such operator always quantize input and so generate
                    quantized output. Also, the True behavior could be disabled per node using the nodes_to_exclude.
                MatMulConstBOnly = True/False:
                    Default is False for static mode. If enabled, only MatMul with const B will be quantized.
                AddQDQPairToWeight = True/False :
                    Default is False which quantizes floating-point weight and feeds it to solely inserted
                    DeQuantizeLinear node. If True, it remains floating-point weight and inserts both
                    QuantizeLinear/DeQuantizeLinear nodes to weight.
                OpTypesToExcludeOutputQuantization = list of op type :
                    Default is []. If any op type is specified, it won't quantize the output of ops with this
                    specific op types.
                DedicatedQDQPair = True/False :
                    Default is False. When inserting QDQ pair, multiple nodes can share a single QDQ pair as their
                    inputs. If True, it will create identical and dedicated QDQ pair for each node.
                QDQOpTypePerChannelSupportToAxis = dictionary :
                    Default is {}. Set channel axis for specific op type, for example: {'MatMul': 1}, and it's
                    effective only when per channel quantization is supported and per_channel is True. If specific
                    op type supports per channel quantization but not explicitly specified with channel axis,
                    default channel axis will be used.
                CalibTensorRangeSymmetric = True/False :
                    Default is False. If enabled, the final range of tensor during calibration will be explicitly
                    set to symmetric to central point "0".
                CalibStridedMinMax = Optional[int] :
                    Default is None. If set to an integer, during calculation of the min-max, only stride amount of
                    data will be used and then all results will be merged in the end.
                CalibMovingAverage = True/False :
                    Default is False. If enabled, the moving average of the minimum and maximum values will be
                    computed when the calibration method selected is MinMax.
                CalibMovingAverageConstant = float :
                    Default is 0.01. Constant smoothing factor to use when computing the moving average of the
                    minimum and maximum values. Effective only when the calibration method selected is MinMax and
                    when CalibMovingAverage is set to True.
                CalibMaxIntermediateOutputs = Optional[int] :
                    Default is None. If set to an integer, during calculation of the min-max range of the tensors
                    it will load at max value number of outputs before computing and merging the range. This will
                    produce the same result as all computing with None, but is more memory efficient.
                SmoothQuant = True/False :
                    Default is False. If enabled, SmoothQuant algorithm will be applied before quantization to do
                    fake input channel quantization.
                SmoothQuantAlpha = float :
                    Default is 0.5. It only works if SmoothQuant is True. It controls the difficulty of weight
                    and activation quantization. A larger alpha value could be used on models with more significant
                    activation outliers to migrate more quantization difficulty to weights.
                SmoothQuantFolding = True/False :
                    Default is True. It only works if SmoothQuant is True. If enabled, inserted Mul ops during
                    SmoothQuant will be folded into the previous op if the previous op is foldable.
                UseQDQContribOps = True/False :
                    Default is False. If enabled, the inserted QuantizeLinear and DequantizeLinear ops will have the
                    `com.microsoft` domain, which forces use of ONNX Runtime's QuantizeLinear and DequantizeLinear
                    contrib op implementations. The contrib op implementations may support features not standardized
                    into the ONNX specification (e.g., 16-bit quantization types).
                MinimumRealRange = float|None :
                    Default is None. If set to a floating-point value, the calculation of the quantization parameters
                    (i.e., scale and zero point) will enforce a minimum range between rmin and rmax. If (rmax - rmin)
                    is less than the specified minimum range, rmax will be set to rmin + MinimumRealRange. This is
                    necessary for EPs like QNN that require a minimum floating-point range when determining
                    quantization parameters.
                TensorQuantOverrides = dictionary :
                    Default is {}. Set tensor quantization overrides. The key is a tensor name and the value is a
                    list of dictionaries. For per-tensor quantization, the list contains a single dictionary. For
                    per-channel quantization, the list contains a dictionary for each channel in the tensor.
                    Each dictionary contains optional overrides with the following keys and values.
                        'quant_type' = QuantType : The tensor's quantization data type.
                        'scale' =  Float         : The scale value to use. Must also specify `zero_point` if set.
                        'zero_point' = Int       : The zero-point value to use. Must also specify `scale` is set.
                        'symmetric' = Bool       : If the tensor should use symmetric quantization. Invalid if also
                                                   set `scale` or `zero_point`.
                        'reduce_range' = Bool    : If the quantization range should be reduced. Invalid if also
                                                   set `scale` or `zero_point`.
                        'rmax' = Float           : Override the maximum real tensor value in calibration data.
                                                   Invalid if also set `scale` or `zero_point`.
                        'rmin' = Float           : Override the minimum real tensor value in calibration data.
                                                   Invalid if also set `scale` or `zero_point`.
                QDQKeepRemovableActivations = True/False:
                    Default is False. If true, "removable" activations (e.g., Clip or Relu) will not be removed, and
                    will be explicitly represented in the QDQ model. If false, these activations are automatically
                    removed if activations are asymmetrically quantized. Keeping these activations is necessary if
                    optimizations or EP transformations will later remove QuantizeLinear/DequantizeLinear
                    operators from the model.
                QDQDisableWeightAdjustForInt32Bias = True/False:
                    Default is False. If true, QDQ quantizer will not adjust the weight's scale when the bias
                    has a scale (input_scale * weight_scale) that is too small.
    zIOnly Distribution calibration method is supported for float quantization.r   Please consider to run pre-processing before quantization. Refer to example: https://github.com/microsoft/onnxruntime-inference-examples/blob/main/quantization/image_classification/cpu/ReadMe.md ))rG   rF   )rI   rH   )rK   rJ   )rM   rL   )rO   rN   SmoothQuantFNz/neural_compressor.adaptor.ox_utils.smooth_quant.zLneural-compressor is not correctly installed. Please check your environment.)ORTSmoothQuantc               3  L   K    j                         } | D ]  }|d f 
 y wrX   )rf   )data_readerdatar2   re   s     r%   inc_dataloaderz'quantize_static.<locals>.inc_dataloader  s,     '$--(?@K#Dj  $s   !$SmoothQuantAlphag      ?SmoothQuantFoldingTz
ort.quant.)prefixzsq_model.onnxzmodel_input.onnx)save_as_external_datazaugmented_model.onnx)augmented_model_pathr3   r#   r5   CalibStridedMinMaxzTotal data size (z#) is not divisible by stride size (z).)start_index	end_indexzUnexpected type z" for tensors_range and calibrator=zPlease consider pre-processing before quantization. See https://github.com/microsoft/onnxruntime-inference-examples/blob/main/quantization/image_classification/cpu/ReadMe.md )<r   r   r	   Distributionr   r   
QLinearOpslenrk   r   keysr   rd   r`   ra   rb   r   r   r   r   r   r   rt   	importlibimport_module	ExceptionerrorRuntimeErrorre   /neural_compressor.adaptor.ox_utils.smooth_quantr   rg   rm   rr   	transformtempfileTemporaryDirectoryjoinpathas_posixsaverl   r   str
save_modelr   range	set_rangecollect_datacompute_datar
   	TypeErrortyper   r   	QOperatorr   r   quantize_modelsave_model_to_filecleanup)*r~   model_outputr2   r4   r   r   r   r    r   r!   r"   r#   r3   r5   modeq_linear_opsqdq_opsr   pre_processedr   rr   r   r   r   er   r   i
orig_nodes
dataloadersqsq_pathquant_tmp_diroutput_path
calibratorstridetotal_data_sizestartr   tensors_range	quantizerre   s*     `                                      @r%   quantize_staticr     s   r )111[ID[D[5[0===hii!'RM'-2)/R/52&&D3';#<#A.3356{'')*#Cw(>$?@ k4??3 	/{;(k):; 
 9?M	
  9Q8P$TX\iTi]t$$8P   .	v##$UV
 	R	!
 ',kk&6&67&6aff&6
7#%
K\B]../A3GIZIZ[oquIvw--\B7<<(11/BKKM

;1B1B1G1G d1GA166YcKc1G de+D,=>		$	$L	9]k4??3d=14FFGKOO&*
 &K& !%m!4!=!=>T!U!^!^!`-%=-

 ""#7>!"9:O'1, #4_4EEhiohppr!sttq/6:!FN	'11ey1Y''(?@ ;
 ##$;<"//1-5"4#6"77YZ^_iZjYkklm  I 
:L !L{,,,! 
	 ! 
	 OO&&|5MN	
 . /_  	vMMQCq'"mntuu	v 8 !e 
:	9sC   4S+S+0S1 )T&T+T+ET01	T#:$TT#0T9c
                   |	xs i }	|xs g }|xs g }|xs g }t         j                  }
|rt        |      dk(  rt        t	        j
                               }t        | t        j                        rt        |       nt        t        |             }t        |      }|st        j                  d       d|	vrd|	d<   t        ||||
d|t         j"                  d||||	      }|j%                          |j&                  j)                  ||       y)a	  Given an onnx model, create a quantized onnx model and save it into a file

    Args:
        model_input: file path of model or ModelProto to quantize
        model_output: file path of quantized model
        op_types_to_quantize:
            specify the types of operators to quantize, like ['Conv'] to quantize Conv only.
            It quantizes all supported operators by default.
        per_channel: quantize weights per channel
        reduce_range:
            quantize weights with 7-bits. It may improve the accuracy for some models running on non-VNNI machine,
            especially for per-channel mode
        weight_type:
            quantization data type of weight. Please refer to
            https://onnxruntime.ai/docs/performance/quantization.html for more details on data type selection
        nodes_to_quantize:
            List of nodes names to quantize. When this list is not None only the nodes in this list
            are quantized.
            example:
            [
                'Conv__224',
                'Conv__252'
            ]
        nodes_to_exclude:
            List of nodes names to exclude. The nodes in this list will be excluded from quantization
            when it is not None.
        use_external_data_format: option used for large size (>2GB) model. Set to False by default.
        extra_options:
            key value pair dictionary for various options in different case. Current used:
                extra.Sigmoid.nnapi = True/False  (Default is False)
                ActivationSymmetric = True/False: symmetrize calibration data for activations (default is False).
                WeightSymmetric = True/False: symmetrize calibration data for weights (default is True).
                EnableSubgraph = True/False :
                    Default is False. If enabled, subgraph will be quantized. Dynamic mode currently is supported. Will
                    support more in the future.
                ForceQuantizeNoInputCheck = True/False :
                    By default, some latent operators like maxpool, transpose, do not quantize if their input is not
                    quantized already. Setting to True to force such operator always quantize input and so generate
                    quantized output. Also the True behavior could be disabled per node using the nodes_to_exclude.
                MatMulConstBOnly = True/False:
                    Default is True for dynamic mode. If enabled, only MatMul with const B will be quantized.
    r   r   MatMulConstBOnlyTFN)r   
IntegerOpsr   rk   r   r   r`   ra   rb   r   r   r   r   r   r   r   r   r+   r   r   r   )r~   r   r   r   r   r   r!   r"   r#   r5   r   r   r   r   s                 r%   quantize_dynamicr     s   l "'RM'-2)/R/52&&D3';#<#A#$6$;$;$=> k4??3 	/{;(k):; 
 9?M	
 .,0()I OO&&|5MNr'   c                @   t        |t              rt        | ||j                  |j                  |j
                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                         yt        |t              rft!        | ||j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  
       yddlm}m} t        ||      rht        | t(        j*                        r| nt)        j,                  |       } |||      }|j/                          |j0                  j3                  |d       yt5        d      )	a+  Quantize a model with QuantConfig.

    Args:
        model_input (str | Path | ModelProto): Path to the model or ModelProto to quantize.
        model_output (str | Path): Path to save the quantized model.
        quant_config (QuantConfig | WeightOnlyQuantConfig): Quantization Configuration.
    )r3   r4   r    r   r   r!   r"   r   r   r#   r5   )r   r   r!   r"   r   r   r#   r5   r   )MatMul4BitsQuantizerWeightOnlyQuantConfig)algo_configTztInvalid quantization config type, it must be either StaticQuantConfig, DynamicQuantConfig, or WeightOnlyQuantConfig.N)r`   r/   r   r2   r3   r4   r    r   r   r!   r"   r   r   r#   r5   r   r   matmul_4bits_quantizerr   r   ra   rb   loadprocessr   r   r   )r~   r   quant_configr   r   r   quants          r%   quantizer   a  sZ    , 1200)::%22(88$00!-!B!B*<<)::$00%22%1%J%J&44	
" 
L"4	5$00!-!B!B*<<)::$00%22%1%J%J&44	
 	Xl$9:#-k4??#KKQUQZQZ[fQgE(LIEMMOKK**<>@ r'   )r~   str | Path | onnx.ModelProtor2   r   r   zdict[str, Any] | Noner   boolr   zbool | Noner   r   r   r   r   r   r   zfloat | Noner   z&dict[str, list[dict[str, Any]]] | Noner"   zDlist[str] | Callable[[onnx.ModelProto, onnx.NodeProto], bool] | Noner5   zdict | Nonereturnr/   )r4   r   r    r   r   r   )r~   r   r   
str | Pathr2   r   )r~   r   r   r   )r~   r   r   r   r   r   ).
__future__r   re   r   r   pathlibr   typingr   r   ra   	calibrater   r	   r
   r   onnx_quantizerr   qdq_quantizerr   quant_utilsr   r   r   r   r   r   r   registryr   r   r   r   r   r   r/   r7   r+   r,   r   r   r   r8   r   r   r   r-   r'   r%   <module>r      s   #        _ _ ) '   J I >4A 4AnF1 F1X '--,0$$!&$(',#'EI]a!%^-^2^ *	^ ^ "^ ^ ^ !%^ !^ C^ [^ ^  !^B+1 +1\
D OO"&--m-mm 3mf	 "aO-aOaOH8-88 8r'   