o
    dij                     @   s  d Z ddlZddlZddl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 ddlmZ dd	lmZmZmZmZmZ dd
lm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* erxddl+m,Z, e*-e.Z/ddiZ0e1e"2 Z3e1e#2 Z4e1e$2 Z5eG dd dZ6G dd dZ7eG dd dZ8de9defddZ:de9dedefdd Z;			d/d!e9d"ee dee d#eee<  d$eeeee< f f
d%d&Z=G d'd( d(Z>eG d)d* d*Z?G d+d, d,Z@G d-d. d.e(ZAdS )0zPConfiguration classes for graph optimization and quantization with ONNX Runtime.    N)asdict	dataclassfield)Enum)Path)TYPE_CHECKINGAnyDictListOptionalTupleUnion)Versionparse)__version__)CalibraterBaseCalibrationMethodQuantFormatQuantizationMode	QuantType)create_calibrator)IntegerOpsRegistryQDQRegistryQLinearOpsRegistry)FusionOptions   )
BaseConfig)logging)DatasetMatMul   c                   @   s   e Zd ZU dZeed< eed< eed< eed< eed< dZe	e ed< dZ
e	e ed	< dZe	e ed
< dZe	e ed< dZe	e ed< 			ddeeejef de	ee  dedededefddZdS )CalibrationConfiga3  
    CalibrationConfig is the configuration class handling all the ONNX Runtime parameters related to the calibration
    step of static quantization.

    Args:
        dataset_name (`str`):
            The name of the calibration dataset.
        dataset_config_name (`str`):
            The name of the calibration dataset configuration.
        dataset_split (`str`):
            Which split of the dataset is used to perform the calibration step.
        dataset_num_samples (`int`):
            The number of samples composing the calibration dataset.
        method (`CalibrationMethod`):
            The method chosen to calculate the activations quantization parameters using the calibration dataset.
        num_bins (`Optional[int]`, defaults to `None`):
            The number of bins to use when creating the histogram when performing the calibration step using the
            Percentile or Entropy method.
        num_quantized_bins (`Optional[int]`, defaults to `None`):
            The number of quantized bins to use when performing the calibration step using the Entropy method.
        percentile (`Optional[float]`, defaults to `None`):
            The percentile to use when computing the activations quantization ranges when performing the calibration
            step using the Percentile method.
        moving_average (`Optional[bool]`, defaults to `None`):
            Whether to compute the moving average of the minimum and maximum values when performing the calibration step
            using the MinMax method.
        averaging_constant (`Optional[float]`, defaults to `None`):
            The constant smoothing factor to use when computing the moving average of the minimum and maximum values.
            Effective only when the MinMax calibration method is selected and `moving_average` is set to True.
    dataset_namedataset_config_namedataset_splitdataset_num_samplesmethodNnum_binsnum_quantized_bins
percentilemoving_averageaveraging_constantFaugmented_model.onnxonnx_model_pathoperators_to_quantizeuse_external_data_formatforce_symmetric_rangeaugmented_model_namereturnc                 C   sZ   ||pg | j |d}tttdkr&||d< || j| j| j| j| jd|d< t	di |S )N)modelop_types_to_calibratecalibrate_methodaugmented_model_pathz1.10.0r/   )	symmetricr'   r(   r)   r*   r+   extra_options )
r&   r   ort_versionr   r'   r(   r)   r*   r+   r   )selfr-   r.   r/   r0   r1   kwargsr9   r9   o/lsinfo/ai/hellotax_ai/llm_service/venv_embed/lib/python3.10/site-packages/optimum/onnxruntime/configuration.pyr   ^   s   	
z#CalibrationConfig.create_calibrator)FFr,   )__name__
__module____qualname____doc__str__annotations__intr   r'   r   r(   r)   floatr*   boolr+   r   osPathLiker   r
   r   r   r9   r9   r9   r=   r!   2   s8   
 
r!   c                
   @   sr   e Zd Ze	ddddededefdd	Ze	
	
ddddededefddZ	eddddededefddZ
dS )AutoCalibrationConfigF{Gz?datasetr   r*   r+   r2   c              	   C   sn   |rt ttdk rtd|r#d|  krdks#n td| dt| jj| jjt	| j
| jtj||dS )a  
        Args:
            dataset (`Dataset`):
                The dataset to use when performing the calibration step.
            moving_average (`bool`):
                Whether to compute the moving average of the minimum and maximum values.
            averaging_constant (`float`):
                The constant smoothing factor to use when computing the moving average of the minimum and maximum
                values.

        Returns:
            The calibration configuration.
        1.11.0z`MinMax calibration using the moving average method is only implemented for onnxruntime >= 1.11.0r   r    z"Invalid averaging constant value (z) should be within [0, 1])r"   r#   r$   r%   r&   r*   r+   )r   r:   r   NotImplementedError
ValueErrorr!   infobuilder_nameconfig_namerB   splitnum_rowsr   MinMax)rK   r*   r+   r9   r9   r=   minmaxz   s   zAutoCalibrationConfig.minmax   r'   r(   c              	   C   sp   t ttdk rtd|dkrtd| d|dkr$td| dt| jj| jjt	| j
| jtj||dS )a  
        Args:
            dataset (`Dataset`):
                The dataset to use when performing the calibration step.
            num_bins (`int`):
                The number of bins to use when creating the histogram.
            num_quantized_bins (`int`):
                The number of quantized bins used to find the optimal threshold when computing the activations
                quantization ranges.

        Returns:
            The calibration configuration.
        rL   zHEntropy calibration method is only implemented for onnxruntime >= 1.11.0r   Invalid value num_bins () should be >= 1z"Invalid value num_quantized_bins ()r"   r#   r$   r%   r&   r'   r(   )r   r:   r   rM   rN   r!   rO   rP   rQ   rB   rR   rS   r   Entropy)rK   r'   r(   r9   r9   r=   entropy   s   zAutoCalibrationConfig.entropy   -X@r)   c              	   C   s~   t ttdk rtd|dkrtd| dd|  kr"dks+n td| dt| jj| jjt	| j
| jtj||d	S )
a  
        Args:
            dataset (`Dataset`):
                The dataset to use when performing the calibration step.
            num_bins (`int`):
                The number of bins to use when creating the histogram.
            percentile (`float`):
                The percentile to use when computing the activations quantization ranges.

        Returns:
            The calibration configuration.
        rL   zKPercentile calibration method is only implemented for onnxruntime >= 1.11.0r   rW   rX   d   zInvalid value percentile (z) should be within  [0, 100])r"   r#   r$   r%   r&   r'   r)   )r   r:   r   rM   rN   r!   rO   rP   rQ   rB   rR   rS   r   
Percentile)rK   r'   r)   r9   r9   r=   percentiles   s   z!AutoCalibrationConfig.percentilesN)FrJ   )rV   rV   )r[   r\   )r>   r?   r@   staticmethodrF   rE   r!   rU   rD   rZ   r_   r9   r9   r9   r=   rI   y   s4    "%"rI   c                   @   s0  e Zd ZU dZeed< eed< ejZ	eed< e
jZe
ed< dZeed< e
jZe
ed< d	Zeed
< dZeed< dZeed< eedZee ed< eedZee ed< eedZee ed< dZeed< dZeed< edd dZeeef ed< dd Ze de
de
defddZ!e"defddZ#dd Z$dS ) QuantizationConfiga  
    QuantizationConfig is the configuration class handling all the ONNX Runtime quantization parameters.

    Args:
        is_static (`bool`):
            Whether to apply static quantization or dynamic quantization.
        format (`QuantFormat`):
            Targeted ONNX Runtime quantization representation format.
            For the Operator Oriented (QOperator) format, all the quantized operators have their own ONNX definitions.
            For the Tensor Oriented (QDQ) format, the model is quantized by inserting QuantizeLinear / DeQuantizeLinear
            operators.
        mode (`QuantizationMode`, defaults to `QuantizationMode.QLinearOps`):
            Targeted ONNX Runtime quantization mode, default is QLinearOps to match QDQ format.
            When targeting dynamic quantization mode, the default value is `QuantizationMode.IntegerOps` whereas the
            default value for static quantization mode is `QuantizationMode.QLinearOps`.
        activations_dtype (`QuantType`, defaults to `QuantType.QUInt8`):
            The quantization data types to use for the activations.
        activations_symmetric (`bool`, defaults to `False`):
            Whether to apply symmetric quantization on the activations.
        weights_dtype (`QuantType`, defaults to `QuantType.QInt8`):
            The quantization data types to use for the weights.
        weights_symmetric (`bool`, defaults to `True`):
            Whether to apply symmetric quantization on the weights.
        per_channel (`bool`, defaults to `False`):
            Whether we should quantize per-channel (also known as "per-row"). Enabling this can increase overall
            accuracy while making the quantized model heavier.
        reduce_range (`bool`, defaults to `False`):
            Whether to use reduce-range 7-bits integers instead of 8-bits integers.
        nodes_to_quantize (`List[str]`, defaults to `[]`):
            List of the nodes names to quantize. When unspecified, all nodes will be quantized. If empty, all nodes being operators from `operators_to_quantize` will be quantized.
        nodes_to_exclude (`List[str]`, defaults to `[]`):
            List of the nodes names to exclude when applying quantization. The list of nodes in a model can be found loading the ONNX model through onnx.load, or through visual inspection with [netron](https://github.com/lutzroeder/netron).
        operators_to_quantize (`List[str]`):
            List of the operators types to quantize. Defaults to all quantizable operators for the given quantization mode and format. Quantizable operators can be found at https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/registry.py.
        qdq_add_pair_to_weight (`bool`, defaults to `False`):
            By default, floating-point weights are quantized and feed to solely inserted DeQuantizeLinear node.
            If set to True, the floating-point weights will remain and both QuantizeLinear / DeQuantizeLinear nodes
            will be inserted.
        qdq_dedicated_pair (`bool`, defaults to `False`):
            When inserting QDQ pair, multiple nodes can share a single QDQ pair as their inputs. If True, it will
            create an identical and dedicated QDQ pair for each node.
        qdq_op_type_per_channel_support_to_axis (`Dict[str, int]`):
            Set the channel axis for a specific operator type. Effective only when per channel quantization is
            supported and `per_channel` is set to True.
    	is_staticformatmodeactivations_dtypeFactivations_symmetricweights_dtypeTweights_symmetricper_channelreduce_range)default_factorynodes_to_quantizenodes_to_excluder.   qdq_add_pair_to_weightqdq_dedicated_pairc                   C   s   t S N)!ORT_DEFAULT_CHANNEL_FOR_OPERATORSr9   r9   r9   r=   <lambda>$  s    zQuantizationConfig.<lambda>'qdq_op_type_per_channel_support_to_axisc                 C   s   t | j| j t| j| j| j t| jdkr(t| j| j	| j| j\}}}|| _t
| j	tr4t| j	 | _	t
| jtr@t| j | _t
| jtrLt| j | _t
| jtrZt| j | _d S d S Nr   )ensure_valid_mode_or_raiserb   rd   ensure_valid_data_type_or_raisere   rg   lenr.   default_quantization_parametersrc   
isinstancerB   r   r   r   )r;   _r.   r9   r9   r=   __post_init__'  s    
z QuantizationConfig.__post_init__r2   c                 C   s.   | t jkrdnd d|t jkrd S d S )Ns8u8/)r   QInt8)re   rg   r9   r9   r=   quantization_type_str;  s   z(QuantizationConfig.quantization_type_strc                 C   s   | j o| jS rp   )rf   rh   r;   r9   r9   r=   use_symmetric_calibrationC  s   z,QuantizationConfig.use_symmetric_calibrationc                 C   s.   | j  d| j dt| j| j d| j dS )Nz (mode: z
, schema: z, channel-wise: ))rc   rd   ra   r   re   rg   ri   r   r9   r9   r=   __str__G  s   zQuantizationConfig.__str__N)%r>   r?   r@   rA   rF   rC   r   r   
QLinearOpsrd   r   QUInt8re   rf   r   rg   rh   ri   rj   r   listrl   r
   rB   rm   r.   rn   ro   rs   r	   rD   r{   r`   r   propertyr   r   r9   r9   r9   r=   ra      s2   
 .ra   use_static_quantizationrd   c                 C   s   | s|t jkrtdd S d S )NzInvalid combination of use_static_quantization = False and mode = QuantizationMode.QLinearOps. OnnxRuntime dynamic quantization requires mode = QuantizationMode.IntegerOps)r   r   rN   )r   rd   r9   r9   r=   ru   P  s
   ru   re   rg   c                 C   sB   | s|t jkrtd| r|t jkr|t jkrtdd S d S d S )NzInvalid combination of use_static_quantization = False and activations_dtype = QuantType.QInt8. OnnxRuntime dynamic quantization requires activations_dtype = QuantType.QUInt8zInvalid combination of use_static_quantization = True, activations_dtype = QuantType.QInt8 and weights_dtype = QuantType.QUInt8.OnnxRuntime static quantization does not support activations_dtype = QuantType.QInt8 with weights_dtype = QuantType.QUInt8.)r   r   rN   r   )r   re   rg   r9   r9   r=   rv   [  s   rv   rb   rc   r.   r2   c                 C   s   |d u r| r	t jnt j}|d u r| rtjntj}|d u s"t|dkr?| r,|t jkr,t}n| r6|tjkr6t}n	| s?|tjkr?t	}|||fS rt   )
r   QDQ	QOperatorr   r   
IntegerOpsrw   'ORT_DEFAULT_OPS_STATIC_QUANTIZATION_QDQ(ORT_DEFAULT_OPS_STATIC_QUANTIZATION_QOPS$ORT_DEFAULT_OPS_DYNAMIC_QUANTIZATION)rb   rc   rd   r.   r9   r9   r=   rx   s  s   
rx   c                   @   s  e Zd Ze						ddededededeee  d	eee  d
eee  fddZe							ddedededededeee  d	eee  d
eee  de	fddZ
e							ddedededededeee  d	eee  d
eee  de	fddZe						ddededededeee  d	eee  d
eee  de	fddZe				ddedeee  d	eee  d
eee  de	f
ddZdS )AutoQuantizationConfigFTNrb   use_symmetric_activationsuse_symmetric_weightsri   rl   rm   r.   c           	      C   >   t | |d\}}}t| ||tj|tj||d|pg |pg |dS )a   
        Creates a [`~onnxruntime.QuantizationConfig`] fit for ARM64.

        Args:
            is_static (`bool`):
                Boolean flag to indicate whether we target static or dynamic quantization.
            use_symmetric_activations (`bool`, defaults to `False`):
                Whether to use symmetric quantization for activations.
            use_symmetric_weights (`bool`, defaults to `True`):
                Whether to use symmetric quantization for weights.
            per_channel (`bool`, defaults to `True`):
                Whether we should quantize per-channel (also known as "per-row"). Enabling this can
                increase overall accuracy while making the quantized model heavier.
            nodes_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to quantize. If `None`, all nodes being operators from `operators_to_quantize` will be quantized.
            nodes_to_exclude (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to exclude from quantization. The list of nodes in a model can be found loading the ONNX model through onnx.load, or through visual inspection with [netron](https://github.com/lutzroeder/netron).
            operators_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Type of nodes to perform quantization on. By default, all the quantizable operators will be quantized. Quantizable operators can be found at https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/registry.py.
        r.   Frb   rc   rd   re   rf   rg   rh   ri   rj   rl   rm   r.   rx   ra   r   r   r   	rb   r   r   ri   rl   rm   r.   rc   rd   r9   r9   r=   arm64  s"   zAutoQuantizationConfig.arm64rj   r2   c           
      C   s>   t | |d\}}	}t| ||	tj|tj||||pg |pg |dS )a  
        Creates a [`~onnxruntime.QuantizationConfig`] fit for CPU with AVX2 instruction set.

        Args:
            is_static (`bool`):
                Boolean flag to indicate whether we target static or dynamic quantization.
            use_symmetric_activations (`bool`, defaults to `False`):
                Whether to use symmetric quantization for activations.
            use_symmetric_weights (`bool`, defaults to `True`):
                Whether to use symmetric quantization for weights.
            per_channel (`bool`, defaults to `True`):
                Whether we should quantize per-channel (also known as "per-row"). Enabling this can
                increase overall accuracy while making the quantized model heavier.
            reduce_range (`bool`, defaults to `False`):
                Indicate whether to use 8-bits integers (False) or reduce-range 7-bits integers (True).
                As a baseline, it is always recommended testing with full range (reduce_range = False) and then, if
                accuracy drop is significant, to try with reduced range (reduce_range = True).
                Intel's CPUs using AVX512 (non VNNI) can suffer from saturation issue when invoking
                the VPMADDUBSW instruction. To counter this, one should use 7-bits rather than 8-bits integers.
            nodes_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to quantize. If `None`, all nodes being operators from `operators_to_quantize` will be quantized.
            nodes_to_exclude (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to exclude from quantization. The list of nodes in a model can be found loading the ONNX model through onnx.load, or through visual inspection with [netron](https://github.com/lutzroeder/netron).
            operators_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Type of nodes to perform quantization on. By default, all the quantizable operators will be quantized. Quantizable operators can be found at https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/registry.py.
        r   r   )rx   ra   r   r   
rb   r   r   ri   rj   rl   rm   r.   rc   rd   r9   r9   r=   avx2  "   %zAutoQuantizationConfig.avx2c           
      C   s>   t | |d\}}	}t| ||	tj|tj||||pg |pg |dS )a  
        Creates a [`~onnxruntime.QuantizationConfig`] fit for CPU with AVX512 instruction set.

        Args:
            is_static (`bool`):
                Boolean flag to indicate whether we target static or dynamic quantization.
            use_symmetric_activations (`bool`, defaults to `False`):
                Whether to use symmetric quantization for activations.
            use_symmetric_weights (`bool`, defaults to `True`):
                Whether to use symmetric quantization for weights.
            per_channel (`bool`, defaults to `True`):
                Whether we should quantize per-channel (also known as "per-row"). Enabling this can
                increase overall accuracy while making the quantized model heavier.
            reduce_range (`bool`, defaults to `False`):
                Indicate whether to use 8-bits integers (False) or reduce-range 7-bits integers (True).
                As a baseline, it is always recommended testing with full range (reduce_range = False) and then, if
                accuracy drop is significant, to try with reduced range (reduce_range = True).
                Intel's CPUs using AVX512 (non VNNI) can suffer from saturation issue when invoking
                the VPMADDUBSW instruction. To counter this, one should use 7-bits rather than 8-bits integers.
            nodes_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to quantize. If `None`, all nodes being operators from `operators_to_quantize` will be quantized.
            nodes_to_exclude (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to exclude from quantization. The list of nodes in a model can be found loading the ONNX model through onnx.load, or through visual inspection with [netron](https://github.com/lutzroeder/netron).
            operators_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Type of nodes to perform quantization on. By default, all the quantizable operators will be quantized. Quantizable operators can be found at https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/registry.py.
        r   r   r   r   r9   r9   r=   avx512  r   zAutoQuantizationConfig.avx512c           	      C   r   )a  
        Creates a [`~onnxruntime.QuantizationConfig`] fit for CPU with AVX512-VNNI instruction set.

        When targeting Intel AVX512-VNNI CPU underlying execution engine leverage the CPU instruction VPDPBUSD to
        compute  \i32 += i8(w) * u8(x)\ within a single instruction.

        AVX512-VNNI (AVX512 Vector Neural Network Instruction)
        is an x86 extension Instruction set and is a part of the AVX-512 ISA.

        AVX512 VNNI is designed to accelerate convolutional neural network for INT8 inference.

        Args:
            is_static (`bool`):
                Boolean flag to indicate whether we target static or dynamic quantization.
            use_symmetric_activations (`bool`, defaults to `False`):
                Whether to use symmetric quantization for activations.
            use_symmetric_weights (`bool`, defaults to `True`):
                Whether to use symmetric quantization for weights.
            per_channel (`bool`, defaults to `True`):
                Whether we should quantize per-channel (also known as "per-row"). Enabling this can
                increase overall accuracy while making the quantized model heavier.
            nodes_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to quantize. If `None`, all nodes being operators from `operators_to_quantize` will be quantized.
            nodes_to_exclude (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to exclude from quantization. The list of nodes in a model can be found loading the ONNX model through onnx.load, or through visual inspection with [netron](https://github.com/lutzroeder/netron).
            operators_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Type of nodes to perform quantization on. By default, all the quantizable operators will be quantized. Quantizable operators can be found at https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/registry.py.
        r   Fr   r   r   r9   r9   r=   avx512_vnni.  s"   &z"AutoQuantizationConfig.avx512_vnnic                 C   sB   t d|d\}}}td||tjdtjd| d|pg |pg |dddS )a  
        Creates a [`~onnxruntime.QuantizationConfig`] fit for TensorRT static quantization, targetting NVIDIA GPUs.

        Args:
            per_channel (`bool`, defaults to `True`):
                Whether we should quantize per-channel (also known as "per-row"). Enabling this can
                increase overall accuracy while making the quantized model heavier.
            nodes_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to quantize. If `None`, all nodes being operators from `operators_to_quantize` will be quantized.
            nodes_to_exclude (`Optional[List[str]]`, defaults to `None`):
                Specific nodes to exclude from quantization. The list of nodes in a model can be found loading the ONNX model through onnx.load, or through visual inspection with [netron](https://github.com/lutzroeder/netron).
            operators_to_quantize (`Optional[List[str]]`, defaults to `None`):
                Type of nodes to perform quantization on. By default, all the quantizable operators will be quantized. Quantizable operators can be found at https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/registry.py.
        T)rb   r.   F)rb   rc   rd   re   rf   rg   rh   ri   rj   rl   rm   r.   rn   ro   )rx   ra   r   r   )ri   rl   rm   r.   rc   rd   r9   r9   r=   tensorrtg  s&   zAutoQuantizationConfig.tensorrt)FTTNNN)FTTFNNN)TNNN)r>   r?   r@   r`   rF   r   r
   rB   r   ra   r   r   r   r   r9   r9   r9   r=   r     s    


2


	7


	7


8


r   c                   @   s  e Zd ZU dZdZeed< dZeed< dZ	eed< dZ
ee ed< d	Zeed
< dZee ed< dZeed< dZee ed< dZeed< dZee ed< dZeed< dZee ed< dZeed< dZee ed< dZeed< dZee ed< dZeed< dZee ed< d	Zeed< dZeed< dZeed< dZeed< d	Zeed< dZeed< dZeed< dZ eed< dZ!eed< d	Z"eed < d	Z#eed!< dZ$eed"< d#d$ Z%d%e&d&e'fd'd(Z(dS ))OptimizationConfiga<  
    OptimizationConfig is the configuration class handling all the ONNX Runtime optimization parameters.
    There are two stacks of optimizations:
        1. The ONNX Runtime general-purpose optimization tool: it can work on any ONNX model.
        2. The ONNX Runtime transformers optimization tool: it can only work on a subset of transformers models.

    Attributes:
        optimization_level (`int`, defaults to 1):
            Optimization level performed by ONNX Runtime of the loaded graph.
            Supported optimization level are 0, 1, 2 and 99.
                - 0: will disable all optimizations
                - 1: will enable basic optimizations
                - 2: will enable basic and extended optimizations, including complex node fusions applied to the nodes
                assigned to the CPU or CUDA execution provider, making the resulting optimized graph hardware dependent
                - 99: will enable all available optimizations including layout optimizations
        optimize_for_gpu (`bool`, defaults to `False`):
            Whether to optimize the model for GPU inference.
            The optimized graph might contain operators for GPU or CPU only when `optimization_level` > 1.
        fp16 (`bool`, defaults to `False`):
            Whether all weights and nodes should be converted from float32 to float16.
        enable_transformers_specific_optimizations (`bool`, defaults to `True`):
            Whether to only use `transformers` specific optimizations on top of ONNX Runtime general optimizations.
        disable_gelu_fusion (`bool`, defaults to `False`):
            Whether to disable the Gelu fusion.
        disable_layer_norm_fusion (`bool`, defaults to `False`):
            Whether to disable Layer Normalization fusion.
        disable_attention_fusion (`bool`, defaults to `False`):
            Whether to disable Attention fusion.
        disable_skip_layer_norm_fusion (`bool`, defaults to `False`):
            Whether to disable SkipLayerNormalization fusion.
        disable_bias_skip_layer_norm_fusion (`bool`, defaults to `False`):
            Whether to disable Add Bias and SkipLayerNormalization fusion.
        disable_bias_gelu_fusion (`bool`, defaults to `False`):
            Whether to disable Add Bias and Gelu / FastGelu fusion.
        disable_embed_layer_norm_fusion (`bool`, defaults to `True`):
            Whether to disable EmbedLayerNormalization fusion.
            The default value is set to `True` since this fusion is incompatible with ONNX Runtime quantization.
        enable_gelu_approximation (`bool`, defaults to `False`):
            Whether to enable Gelu / BiasGelu to FastGelu conversion.
            The default value is set to `False` since this approximation might slightly impact the model's accuracy.
        use_mask_index (`bool`, defaults to `False`):
            Whether to use mask index instead of raw attention mask in the attention operator.
        no_attention_mask (`bool`, defaults to `False`):
            Whether to not use attention masks. Only works for bert model type.
        disable_embed_layer_norm (`bool`, defaults to `True`):
            Whether to disable EmbedLayerNormalization fusion.
            The default value is set to `True` since this fusion is incompatible with ONNX Runtime quantization
        disable_shape_inference (`bool`, defaults to `False`):
            Whether to disable symbolic shape inference.
            The default value is set to `False` but symbolic shape inference might cause issues sometimes.
        use_multi_head_attention (`bool`, defaults to `False`):
            Experimental argument. Use MultiHeadAttention instead of Attention operator, which has merged weights for Q/K/V projection,
            which might be faster in some cases since 3 MatMul is merged into one."
            "Note that MultiHeadAttention might be slower than Attention when qkv are not packed. "
        enable_gemm_fast_gelu_fusion (`bool`, defaults to `False`):
            Enable GemmfastGelu fusion.
        use_raw_attention_mask (`bool`, defaults to `False`):
            Use raw attention mask. Use this option if your input is not right-side padding. This might deactivate fused attention and get worse performance.
        disable_group_norm_fusion (`bool`, defaults to `True`):
            Do not fuse GroupNorm. Only works for model_type=unet.
        disable_packed_kv (`bool`, defaults to `True`):
            Do not use packed kv in cross attention. Only works for model_type=unet.
        disable_rotary_embeddings (`bool`, defaults to `False`):
            Whether to disable Rotary Embedding fusion.
    r    optimization_levelFoptimize_for_gpufp16Noptimize_with_onnxruntime_onlyT*enable_transformers_specific_optimizationsdisable_geludisable_gelu_fusiondisable_layer_normdisable_layer_norm_fusiondisable_attentiondisable_attention_fusiondisable_skip_layer_normdisable_skip_layer_norm_fusiondisable_bias_skip_layer_norm#disable_bias_skip_layer_norm_fusiondisable_bias_geludisable_bias_gelu_fusiondisable_embed_layer_normdisable_embed_layer_norm_fusionenable_gelu_approximationuse_mask_indexno_attention_maskdisable_shape_inferenceuse_multi_head_attentionenable_gemm_fast_gelu_fusionuse_raw_attention_maskdisable_group_norm_fusiondisable_packed_kvdisable_rotary_embeddingsc                    sj   d fdd	}|dddd d |dd	 |d
d |dd |dd |dd |dd	 |dd d S )Nc                    sl   t  | d d ur4|d u rdd }|}t ||t  |  t|  d| d| dt  | dt d S d S )Nc                 S   s   | S rp   r9   xr9   r9   r=   identity  s   zWOptimizationConfig.__post_init__.<locals>.deprecate_renamed_attribute.<locals>.identityz will be deprecated soon, use z
 instead, z is set to .)getattrsetattrwarningswarnFutureWarning)old_namenew_namemapping_funcr   r   r9   r=   deprecate_renamed_attribute  s   zEOptimizationConfig.__post_init__.<locals>.deprecate_renamed_attributer   r   c                 S   s   |  S rp   r9   r   r9   r9   r=   rr     s    z2OptimizationConfig.__post_init__.<locals>.<lambda>)r   r   r   r   r   r   r   r   r   r   r   r   r   r   rp   r9   )r;   r   r9   r   r=   r{     s   





z OptimizationConfig.__post_init__
model_typer2   c           	      C   s   G dd d}| }||_ ddddddd	d
dddddd}| D ]\}}t||t| | q!| j D ]\}}t||r>q4t||| q4t|S )Nc                   @   s   e Zd ZdS )z5OptimizationConfig.create_fusion_options.<locals>.BoxN)r>   r?   r@   r9   r9   r9   r=   Box%  s    r   r   r   r   r   r   r   r   disable_group_normr   r   enable_gemm_fast_gelur   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   )r   itemsr   r   __dict__hasattrr   r   )	r;   r   r   argsattribute_map	attr_namefusion_attr_nameattrvaluer9   r9   r=   create_fusion_options$  s0   

z(OptimizationConfig.create_fusion_options))r>   r?   r@   rA   r   rD   rC   r   rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r{   rB   r   r   r9   r9   r9   r=   r     sD   
 Br   c                   @   s   e Zd ZdZdddddddddddddddd	Zedd
ededefddZ	eddedefddZ
eddedefddZeddedefddZeddedefddZdS )AutoOptimizationConfigz8
    Factory to create common `OptimizationConfig`.
    r    F)r   r   r   T)r   r   r   )r   r   r   r   )O1O2O3O4r   for_gpur2   c                 K   sd   || j vrtdd| j   d| |dkr$|du r"td d}td
d|i| j | |S )a  
        Creates an [`~OptimizationConfig`] with pre-defined arguments according to an optimization level.

        Args:
            optimization_level (`str`):
                The optimization level, the following values are allowed:
                - O1: Basic general optimizations
                - O2: Basic and extended general optimizations, transformers-specific fusions.
                - O3: Same as O2 with Fast Gelu approximation.
                - O4: Same as O3 with mixed precision.
            for_gpu (`bool`, defaults to `False`):
                Whether the model to optimize will run on GPU, some optimizations depends on the hardware the model
                will run on. Only needed for optimization_level > 1.
            kwargs (`Dict[str, Any]`):
                Arguments to provide to the [`~OptimizationConfig`] constructor.

        Returns:
            `OptimizationConfig`: The `OptimizationConfig` corresponding to the requested optimization level.
        zoptimization_level must be in z, z, got r   FzUOverridding for_gpu=False to for_gpu=True as half precision is available only on GPU.Tr   Nr9   )_LEVELSrN   joinkeysloggerwarningr   )clsr   r   r<   r9   r9   r=   with_optimization_level_  s   

z.AutoOptimizationConfig.with_optimization_levelc                 K      | j dd|i|S )a$  
        Creates an O1 [`~OptimizationConfig`].

        Args:
            for_gpu (`bool`, defaults to `False`):
                Whether the model to optimize will run on GPU, some optimizations depends on the hardware the model
                will run on. Only needed for optimization_level > 1.
            kwargs (`Dict[str, Any]`):
                Arguments to provide to the [`~OptimizationConfig`] constructor.

        Returns:
            `OptimizationConfig`: The `OptimizationConfig` corresponding to the O1 optimization level.
        r   r   N)r   r   r   r   r<   r9   r9   r=   r        zAutoOptimizationConfig.O1c                 K   r   )a$  
        Creates an O2 [`~OptimizationConfig`].

        Args:
            for_gpu (`bool`, defaults to `False`):
                Whether the model to optimize will run on GPU, some optimizations depends on the hardware the model
                will run on. Only needed for optimization_level > 1.
            kwargs (`Dict[str, Any]`):
                Arguments to provide to the [`~OptimizationConfig`] constructor.

        Returns:
            `OptimizationConfig`: The `OptimizationConfig` corresponding to the O2 optimization level.
        r   r   N)r   r   r   r9   r9   r=   r     r   zAutoOptimizationConfig.O2c                 K   r   )a$  
        Creates an O3 [`~OptimizationConfig`].

        Args:
            for_gpu (`bool`, defaults to `False`):
                Whether the model to optimize will run on GPU, some optimizations depends on the hardware the model
                will run on. Only needed for optimization_level > 1.
            kwargs (`Dict[str, Any]`):
                Arguments to provide to the [`~OptimizationConfig`] constructor.

        Returns:
            `OptimizationConfig`: The `OptimizationConfig` corresponding to the O3 optimization level.
        r   r   N)r   r   r   r9   r9   r=   r     r   zAutoOptimizationConfig.O3c                 K   r   )a$  
        Creates an O4 [`~OptimizationConfig`].

        Args:
            for_gpu (`bool`, defaults to `False`):
                Whether the model to optimize will run on GPU, some optimizations depends on the hardware the model
                will run on. Only needed for optimization_level > 1.
            kwargs (`Dict[str, Any]`):
                Arguments to provide to the [`~OptimizationConfig`] constructor.

        Returns:
            `OptimizationConfig`: The `OptimizationConfig` corresponding to the O4 optimization level.
        r   r   N)r   r   r   r9   r9   r=   r     r   zAutoOptimizationConfig.O4N)F)T)r>   r?   r@   rA   r   classmethodrB   rF   r   r   r   r   r   r   r9   r9   r9   r=   r   D  s8     r   c                       s~   e Zd ZdZdZdZ					ddee deded	ee	 d
ee
 f
 fddZedefddZdeeef fddZ  ZS )	ORTConfiga  
    ORTConfig is the configuration class handling all the ONNX Runtime parameters related to the ONNX IR model export,
    optimization and quantization parameters.

    Attributes:
        opset (`Optional[int]`, defaults to `None`):
            ONNX opset version to export the model with.
        use_external_data_format (`bool`, defaults to `False`):
            Allow exporting model >= than 2Gb.
        one_external_file (`bool`, defaults to `True`):
            When `use_external_data_format=True`, whether to save all tensors to one external file.
            If false, save each tensor to a file named with the tensor name.
            (Can not be set to `False` for the quantization)
        optimization (`Optional[OptimizationConfig]`, defaults to `None`):
            Specify a configuration to optimize ONNX Runtime model
        quantization (`Optional[QuantizationConfig]`, defaults to `None`):
            Specify a configuration to quantize ONNX Runtime model
    zort_config.jsonNFTopsetr/   one_external_fileoptimizationquantizationc                    s   t    || _|| _|| _t|tr|rtdi || _nt|tr'|| _n|s-d | _n	t	dt
| t|trF|rFtdi || _nt|trO|| _n|sUd | _n	t	dt
| |dd | _d S )Nz`Optional argument `optimization` must be a dictionary or an instance of OptimizationConfig, got z`Optional argument `quantization` must be a dictionary or an instance of QuantizationConfig, got optimum_versionr9   )super__init__r   r/   r   ry   dictr   r   rN   typera   r   popr   )r;   r   r/   r   r   r   r<   	__class__r9   r=   r     s.   
	

zORTConfig.__init__r2   c                 C   sj   i }| d u r|S t | tr| S t|  D ]\}}t |tr"|j}nt |tr.dd |D }|||< q|S )Nc                 S   s    g | ]}t |tr|jn|qS r9   )ry   r   name).0elemr9   r9   r=   
<listcomp>  s     z/ORTConfig.dataclass_to_dict.<locals>.<listcomp>)ry   r   r   r   r   r   r   )config
new_configkvr9   r9   r=   dataclass_to_dict  s   



zORTConfig.dataclass_to_dictc                 C   s:   | j | j| j| | j| | jd}| jr| j|d< |S )N)r   r/   r   r   r   r   )r   r/   r   r   r   r   r   )r;   dict_configr9   r9   r=   to_dict  s   


zORTConfig.to_dict)NFTNN)r>   r?   r@   rA   CONFIG_NAMEFULL_CONFIGURATION_FILEr   rD   rF   r   ra   r   r`   r   r   r	   rB   r   r  __classcell__r9   r9   r   r=   r     s.    %r   )NNN)BrA   rG   r   dataclassesr   r   r   enumr   pathlibr   typingr   r   r	   r
   r   r   r   packaging.versionr   r   onnxruntimer   r:   onnxruntime.quantizationr   r   r   r   r   "onnxruntime.quantization.calibrater   !onnxruntime.quantization.registryr   r   r   'onnxruntime.transformers.fusion_optionsr   configuration_utilsr   utilsr   datasetsr   
get_loggerr>   r   rq   r   r   r   r   r   r!   rI   ra   rF   ru   rv   rB   rx   r   r   r   r   r9   r9   r9   r=   <module>   st   $
Flj


   / 