U
    9%e
S                     @   s  d dl Z d dl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 d dlZd dlmZmZ ddlmZ dd	lmZmZmZmZ d
dlmZ e rddlmZ ddlmZ e rddlm Z  erddl!m"Z" ddl#m$Z$ ddl%m&Z& e'e(Z)edZ*edddZ+d+ed dee,ede-ee
e- e
e- f dddZ.d,ed dee,edee
e- e
e- f dd d!Z/d-ed ed" ee,ede-ee
e- e
e- f dd#d$Z0d.eed ed" ee
e- e1dd%d&d'Z2ed" e	e- ee3e
e- f d(d)d*Z4dS )/    N)	signature)chain)Path)TYPE_CHECKINGIterableListTupleUnion)Versionparse   )PreTrainedTokenizerBase)
TensorTypeis_tf_availableis_torch_availablelogging   )
OnnxConfig)PreTrainedModel)is_torch_less_than_1_11)TFPreTrainedModel)FeatureExtractionMixin)ProcessorMixin)PreTrainedTokenizerz1.4.0)minimum_versionc                 C   sX   z6ddl }t|j}|tk r4td|j d|  dW n tk
rR   tdY nX dS )z
    Check onnxruntime is installed and if the installed version match is recent enough

    Raises:
        ImportError: If onnxruntime is not installed or too old version is found
    r   Nz*We found an older version of onnxruntime (z&) but we require onnxruntime to be >= zp to enable all the conversions options.
Please update onnxruntime by running `pip install --upgrade onnxruntime`zonnxruntime doesn't seem to be currently installed. Please install the onnxruntime by running `pip install onnxruntime` and relaunch the conversion.)onnxruntimer   __version__ORT_QUANTIZE_MINIMUM_VERSIONImportError)r   r   Zort_version r   X/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/onnx/convert.pycheck_onnxruntime_requirements6   s    
r!   cpu)r   r   r   r   r   )preprocessormodelconfigopsetoutput	tokenizerdevicereturnc                    s  t | tr|dk	rtd|dk	r<tdt td |} tt	|t
rddlddlm} tdj   D d|j_|  |jdk	rtd	t|j d
 |j D ],\}}	td| d|	  t|j||	 q|j| tjd}
   j	dkrj r|  i }|
 D ]h\}}t |trbt fdd|D ||< n4t |t r fdd|D ||< n| ||< q0|}
t!||
" \}}t#|j$" }|std|%  t&rvzP|||
f|' t#|j(" |t)t*|j( |j$ d|+|, d|d
 W nH t-k
rr } z(t.|}|dkr^d}t-|n|W 5 d}~X Y nX n>|||
f|' t#|j(" |t)t*|j( |j$ d|d |/  W 5 Q R X ||fS )a  
    Export a PyTorch model to an ONNX Intermediate Representation (IR)

    Args:
        preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
            The preprocessor used for encoding the data.
        model ([`PreTrainedModel`]):
            The model to export.
        config ([`~onnx.config.OnnxConfig`]):
            The ONNX configuration associated with the exported model.
        opset (`int`):
            The version of the ONNX operator set to use.
        output (`Path`):
            Directory to store the exported ONNX model.
        device (`str`, *optional*, defaults to `cpu`):
            The device on which the ONNX model will be exported. Either `cpu` or `cuda`.

    Returns:
        `Tuple[List[str], List[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
        the ONNX configuration.
    NKYou cannot provide both a tokenizer and a preprocessor to export the model.tThe `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use `preprocessor` instead.SOverwriting the `preprocessor` argument with `tokenizer` to generate dummmy inputs.r   )exportzUsing framework PyTorch: TOverriding  configuration item(s)	-  -> 	frameworkcudac                 3   s(   | ] }t |jr| nd V  qd S N
isinstanceZTensorto.0xr)   torchr   r    	<genexpr>   s    z!export_pytorch.<locals>.<genexpr>c                    s$   g | ]}t  fd d|D qS )c                 3   s(   | ] }t |jr| nd V  qd S r6   r7   r:   r=   r   r    r?      s     z,export_pytorch.<locals>.<listcomp>.<genexpr>)tuple)r;   tr=   r   r    
<listcomp>   s    z"export_pytorch.<locals>.<listcomp>z%Model and config inputs doesn't match)finput_namesoutput_namesdynamic_axesdo_constant_foldinguse_external_data_formatZenable_onnx_checkeropset_versionzExporting model exceed maximum protobuf size of 2GB. Please call torch.onnx.export without setting use_external_data_format parameter.zExporting model exceed maximum protobuf size of 2GB. Please call torch.onnx.export without setting use_external_data_format parameter or try with torch 1.10+.)rC   rD   rE   rF   rG   rI   )0r8   r   
ValueErrorwarningswarnFutureWarningloggerinfo
issubclasstyper   r>   Z
torch.onnxr.   r   Zno_gradr%   return_dictevalvalues_overridelenitemssetattrgenerate_dummy_inputsr   PYTORCHr)   r5   Zis_availabler9   r   r@   r   $ensure_model_and_config_inputs_matchkeyslistoutputsZ	patch_opsr   as_posixinputsdictr   rH   Znum_parametersRuntimeErrorstrrestore_ops)r#   r$   r%   r&   r'   r(   r)   Zonnx_exportoverride_config_keyoverride_config_valuemodel_inputsZmodel_inputs_devicekvinputs_matchmatched_inputsonnx_outputserrmessager   r=   r    export_pytorchS   s    





rn   )r   r   r   )r#   r$   r%   r&   r'   r(   r*   c                    s2  ddl }ddl ddl}t| tr2|dk	r2td|dk	rTtdt t	
d |} d|j_|jdk	rt	
dt|j d |j D ],\}}	t	
d	| d
|	  t|j||	 q|j| tjd}
t||
 \}}t|j } fdd|
 D }|jj|||d\}}|||  |  ||fS )a  
    Export a TensorFlow model to an ONNX Intermediate Representation (IR)

    Args:
        preprocessor: ([`PreTrainedTokenizer`] or [`FeatureExtractionMixin`]):
            The preprocessor used for encoding the data.
        model ([`TFPreTrainedModel`]):
            The model to export.
        config ([`~onnx.config.OnnxConfig`]):
            The ONNX configuration associated with the exported model.
        opset (`int`):
            The version of the ONNX operator set to use.
        output (`Path`):
            Directory to store the exported ONNX model.

    Returns:
        `Tuple[List[str], List[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
        the ONNX configuration.
    r   NzIYou cannot provide both a tokenizer and preprocessor to export the model.r,   r-   Tr/   r0   r1   r2   r3   c                    s*   g | ]"\}} j d g|j |j|dqS )N)dtypename)Z
TensorSpecndimro   )r;   keyZtensortfr   r    rB     s    z%export_tensorflow.<locals>.<listcomp>)r&   )onnxZ
tensorflowtf2onnxr8   r   rJ   rK   rL   rM   rN   rO   r%   rR   rT   rU   rV   rW   rX   r   
TENSORFLOWrZ   r[   r\   r]   convertZ
from_kerassaver^   rc   )r#   r$   r%   r&   r'   r(   ru   rv   rd   re   rf   ri   rj   rk   Zinput_signature
onnx_model_r   rs   r    export_tensorflow   s8    


r|   )r   r   c              	   C   s   t  st stdt r4t|tr4|dkr4tdt| trN|dk	rNtd|dk	rpt	dt
 td |} t  rdd	lm} |jstd
|j d|   t  rtt|trt| ||||||dS t rtt|trt| |||||dS dS )a  
    Export a Pytorch or TensorFlow model to an ONNX Intermediate Representation (IR)

    Args:
        preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
            The preprocessor used for encoding the data.
        model ([`PreTrainedModel`] or [`TFPreTrainedModel`]):
            The model to export.
        config ([`~onnx.config.OnnxConfig`]):
            The ONNX configuration associated with the exported model.
        opset (`int`):
            The version of the ONNX operator set to use.
        output (`Path`):
            Directory to store the exported ONNX model.
        device (`str`, *optional*, defaults to `cpu`):
            The device on which the ONNX model will be exported. Either `cpu` or `cuda`. Only PyTorch is supported for
            export on CUDA devices.

    Returns:
        `Tuple[List[str], List[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
        the ONNX configuration.
    zrCannot convert because neither PyTorch nor TensorFlow are not installed. Please install torch or tensorflow first.r5   z1`tf2onnx` does not support export on CUDA device.Nr+   r,   r-   r   )get_torch_versionz@Unsupported PyTorch version for this model. Minimum required is z, got: )r(   r)   )r(   )r   r   r   r8   r   ra   r   rJ   rK   rL   rM   rN   rO   utilsr}   Zis_torch_support_availablewarningZtorch_onnx_minimum_versionrP   rQ   r   rn   r|   )r#   r$   r%   r&   r'   r(   r)   r}   r   r   r    r.     s2    
r.   )r%   r#   reference_modelrz   onnx_named_outputsatolr(   c              	   C   sT  ddl m}m} td t|tr4|d k	r4td|d k	rVt	dt
 td |}t rtt|tr| j|| jd | jd tjd}	n | j|| jd | jd tjd}	| }
|| |
d	gd
}t rtt|tr|d |f |	}i }| D ]F\}}|dkrd}t|ttfr8| ||}|| q|||< q| |	}i }| D ]L\}}t|ttfr| ||}|dd | D  n| ||< qX|||}t|  t| }}|!|s td| d|  td|"| ntd| d t#||D ]0\}}t rPtt|trP|| $  }n||  }td| d |j%|j%kstd|j% d|j%  td|j% d|j% dntd|j% d|j%  t&j'|||ds:t&(t&j)|||d}td| d td t&*t&+||  d!||  d"||  ntd#| d qd S )$Nr   )InferenceSessionSessionOptionszValidating ONNX model...zUYou cannot provide both a tokenizer and a preprocessor to validate the model outputs.r,   r-   r   )Z
batch_sizeZ
seq_lengthr4   ZCPUExecutionProvider)	providersr"   Zpast_key_valuesZpresentc                 S   s   i | ]\}}||  qS r   )numpy)r;   Ztensor_nameZ	pt_tensorr   r   r    
<dictcomp>  s      z*validate_model_outputs.<locals>.<dictcomp>z	-[x] ONNX model output names z do not match reference model zGOutputs doesn't match between reference model and ONNX exported model: u7   	-[✓] ONNX model output names match reference model ()z!	- Validating ONNX Model output "z":z		-[x] shape z doesn't match zQOutputs shape doesn't match between reference model and ONNX exported model: Got z (reference) and z (ONNX)u	   		-[✓] z	 matches )r   z&		-[x] values not close enough (atol: znOutputs values doesn't match between reference model and ONNX exported model: Got max absolute difference of: z for z vs u!   		-[✓] all values close (atol: ),r   r   r   rN   rO   r8   r   rJ   rK   rL   rM   r   rP   rQ   r   rX   Zdefault_fixed_batchZdefault_fixed_sequencer   rY   rw   r^   r9   rV   r\   r@   Z"flatten_output_collection_propertyupdateZ!generate_dummy_inputs_onnxruntimer   runsetr[   issubset
differencezipdetachshapenpZallcloseZlogical_notiscloseZamaxabs)r%   r#   r   rz   r   r   r(   r   r   Zreference_model_inputsoptionssessionZref_outputsZref_outputs_dictrp   valueZ"reference_model_inputs_onnxruntimeZonnx_inputsrk   Zref_outputs_setZonnx_outputs_setZ	ort_valueZ	ref_valueZbad_indicesr   r   r    validate_model_outputs_  s    	






,r   )r$   rf   r*   c                    st   t  r"tt| tr"t| jj}nt| jj}t|}t|	 }|
|}||  fdd|	 D }||fS )z>

    :param model_inputs: :param config_inputs: :return:
    c                    s   g | ]}| kr|qS r   r   )r;   Z	parameterZmatching_inputsr   r    rB     s      z8ensure_model_and_config_inputs_match.<locals>.<listcomp>)r   rP   rQ   r   r   forward
parameterscallr   r[   r   intersection)r$   rf   Zforward_parametersZmodel_inputs_setZforward_inputs_setZis_okZordered_inputsr   r   r    rZ     s    

rZ   )Nr"   )N)Nr"   )N)5rK   inspectr   	itertoolsr   pathlibr   typingr   r   r   r   r	   r   r   Zpackaging.versionr
   r   Ztokenization_utils_baser   r~   r   r   r   r   r%   r   Zmodeling_utilsr   Zpytorch_utilsr   Zmodeling_tf_utilsr   Zfeature_extraction_utilsr   Zprocessing_utilsr   Ztokenization_utilsr   Z
get_logger__name__rN   r   r!   intrb   rn   r|   r.   floatr   boolrZ   r   r   r   r    <module>   s   
#    H  I | 