o
    hK                     @   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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 rSddlmZ e r\ddlmZ erpddl m!Z! ddl"m#Z# ddl$m%Z% e&e'Z(edZ)defddZ*		d3ded dddede+deded de,d ee
e, e
e, f fd!d"Z-	d4ded# dd$dede+deded d ee
e, e
e, f fd%d&Z.		d3ded ded' dede+deded de,d ee
e, e
e, f fd(d)Z/	d4deded d*ed' d+ed,e
e, d-e0ded fd.d/Z1ded' d0e	e, d ee2e
e, f fd1d2Z3dS )5    N)	signature)chain)Path)TYPE_CHECKINGIterableListOptionalTupleUnion)Versionparse   )PreTrainedTokenizerBase)
TensorTypeis_tf_availableis_torch_availablelogging   )
OnnxConfig)PreTrainedModel)TFPreTrainedModel)FeatureExtractionMixin)ProcessorMixin)PreTrainedTokenizerz1.4.0minimum_versionc                 C   sP   zddl }t|j}|tk rtd|j d|  dW dS  ty'   tdw )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   ort_version r    m/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/onnx/convert.pycheck_onnxruntime_requirements5   s   

r"   cpupreprocessor)r   r   r   modelr   configopsetoutput	tokenizerr   devicereturnc                    s:  t | tr|durtd|durtdt td |} tt	|t
rddlddlm} tdj    d|j_|  |jdurstd	t|j d
 |j D ]\}}	td| d|	  t|j||	 q\|j| tjd}
   j	dkrɈj r|  i }|
 D ]1\}}t |trt fdd|D ||< qt |t r fdd|D ||< q| ||< q|}
t!||
" \}}t#|j$" }|std|%  |||
f|& t#|j'" |t(t)|j' |j$ d|d |*  W d   ||fS 1 sw   Y  ||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.ROverwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.r   )exportzUsing framework PyTorch: TOverriding  configuration item(s)	-  -> 	frameworkcudac                 3   *    | ]}t |jr| nd V  qd S N
isinstance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   r7   r8   r9   r=   r@   r    r!   rB      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opset_version)+r:   r   
ValueErrorwarningswarnFutureWarningloggerinfo
issubclasstyper   rA   
torch.onnxr/   r   no_gradr&   return_dictevalvalues_overridelenitemssetattrgenerate_dummy_inputsr   PYTORCHr*   r6   is_availabler<   r	   rC   r   $ensure_model_and_config_inputs_matchkeyslistoutputs	patch_opsas_posixinputsdictr   restore_ops)r$   r%   r&   r'   r(   r)   r*   onnx_exportoverride_config_keyoverride_config_valuemodel_inputsmodel_inputs_devicekvinputs_matchmatched_inputsonnx_outputsr    r@   r!   export_pytorchR   sr   








55rr   )r   r   r   c                    s2  ddl }ddl ddl}t| tr|durtd|dur*tdt t	
d |} d|j_|jdur[t	
dt|j d |j D ]\}}	t	
d	| d
|	  t|j||	 qD|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.   Tr0   r1   r2   r3   r4   c                    s*   g | ]\}} j d g|j |j|dqS )N)dtypename)
TensorSpecndimrs   )r>   keytensortfr    r!   rE      s    z%export_tensorflow.<locals>.<listcomp>)r'   )onnx
tensorflowtf2onnxr:   r   rL   rM   rN   rO   rP   rQ   r&   rV   rX   rY   rZ   r[   r\   r   
TENSORFLOWr_   r`   ra   rb   convert
from_kerassaverd   rg   )r$   r%   r&   r'   r(   r)   r{   r}   ri   rj   rk   ro   rp   rq   input_signature
onnx_model_r    ry   r!   export_tensorflow   s8   


r   )r   r   c              	   C   s   t  s
t s
tdt rt|tr|dkrtdt| tr'|dur'td|dur8t	dt
 td |} t  rQdd	lm} |jsQtd
|j d|   t  rftt|trft| ||||||dS t rztt|tr|t| |||||dS 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.r6   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   r:   r   RuntimeErrorr   rL   rM   rN   rO   rP   rQ   utilsr   is_torch_support_availablewarningtorch_onnx_minimum_versionrR   rS   r   rr   r   )r$   r%   r&   r'   r(   r)   r*   r   r    r    r!   r/      s8   

r/   reference_modelr   onnx_named_outputsatolc              	   C   sF  ddl m}m} td t|tr|d urtd|d ur+t	dt
 td |}t rFtt|trF| j|| jd | jd tjd}	n| j|| jd | jd tjd}	| }
|| |
d	gd
}t rrtt|trr|d |d$i |	}i }| D ]!\}}|dkrd}t|ttfr| ||}|| q|||< q| |	}i }| D ]$\}}t|ttfr| ||}|dd | D  q| ||< q|||}t|  t|}}|!|std| d|  td|"| td| d t#||D ]\}}t r#tt|tr#|| $  }n||  }td| d |j%|j%ksStd|j% d|j%  td|j% d|j% dtd|j% d|j%  t&j'|||dst&(t&j)|||d}td| d td t&*t&+||  d!||  d"||  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   )
batch_size
seq_lengthr5   CPUExecutionProvider)	providersr#   past_key_valuespresentc                 S   s   i | ]	\}}||  qS r    )numpy)r>   tensor_name	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   r   rP   rQ   r:   r   rL   rM   rN   rO   r   rR   rS   r   r\   default_fixed_batchdefault_fixed_sequencer   r]   r~   rd   r<   rZ   ra   rC   "flatten_output_collection_propertyupdate!generate_dummy_inputs_onnxruntimer   runsetr`   issubset
differencezipdetachshapenpallcloselogical_notiscloseamaxabs)r&   r$   r   r   r   r   r)   r   r   reference_model_inputsoptionssessionref_outputsref_outputs_dictrt   value"reference_model_inputs_onnxruntimeonnx_inputsrq   ref_outputs_setonnx_outputs_set	ort_value	ref_valuebad_indicesr    r    r!   validate_model_outputs=  s   	





r   rk   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 | ]}| v r|qS r    r    )r>   	parametermatching_inputsr    r!   rE     s    z8ensure_model_and_config_inputs_match.<locals>.<listcomp>)r   rR   rS   r   r   forward
parameterscallr   r`   r   intersection)r%   rk   forward_parametersmodel_inputs_setforward_inputs_setis_okordered_inputsr    r   r!   r_     s   

r_   )Nr#   r8   )4rM   inspectr   	itertoolsr   pathlibr   typingr   r   r   r   r	   r
   r   r   packaging.versionr   r   tokenization_utils_baser   r   r   r   r   r   r&   r   modeling_utilsr   modeling_tf_utilsr   feature_extraction_utilsr   processing_utilsr   tokenization_utilsr   
get_logger__name__rP   r   r"   intstrrr   r   r/   floatr   boolr_   r    r    r    r!   <module>   s    
#
m
H
I
{