a
    Ž¥»a&þ  ã                   @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZ ddlmZ ddlmZmZmZmZ ddlmZmZmZmZ ddlmZmZmZ daG d	d
„ d
eƒZdd„ Zi Z ej!dd„ ƒZ"dedd„Z#dd„ Z$dd„ Z%dfdd„Z&dd„ Z'dd„ Z(dd„ Z)dd„ Z*d d!„ Z+d"d#„ Z,d$d%„ Z-dgd&d'„Z.d(d)„ Z/d*d+„ Z0d,d-„ Z1d.d/„ Z2d0d1„ Z3dddej4ddddddf
d2d3„Z5dddddej4ej6dddddddddfd4d5„Z7dddddej4ej6ddddddddddfd6d7„Z8dej9ddddfd8d9„Z:ddddddej6ddddddddddfd:d;„Z;d<d=„ Z<e =d>¡Z>d?d@„ Z?dAdB„ Z@dCdD„ ZAdEdF„ ZBdGdH„ ZCdIdJ„ ZDdKdL„ ZEdMdN„ ZFdOdP„ ZGdQdR„ ZHdSdT„ ZIej4fdUdV„ZJdWdX„ ZKdYdZ„ ZLd[d\„ ZMd]d^„ ZNd_d`„ ZOdadb„ ZPdcdd„ ZQeDejRjS_TeKejRjS_UeEejRjV_TeLejRjS_WeMejRjX_YdS )hzÐ
The torch.onnx module contains functions to export models into the ONNX
IR format.  These models can be loaded with the ONNX library and then
converted to models which run on other deep learning frameworks.
é    N)Ústring_classes)Ú_unique_state_dict)ÚONNX_ARCHIVE_MODEL_PROTO_NAMEÚExportTypesÚOperatorExportTypesÚTrainingMode)ÚListTypeÚOptionalTypeÚ"_propagate_and_assign_input_shapesÚ_check_onnx_proto)ÚListÚTupleÚUnionFc                   @   s   e Zd ZdS )ÚONNXCheckerErrorN)Ú__name__Ú
__module__Ú__qualname__© r   r   úJ/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/onnx/utils.pyr      s   r   c                   C   s   t S ©N)Ú__IN_ONNX_EXPORTr   r   r   r   Úis_in_onnx_export    s    r   c              	   c   sÔ   t | tjjƒs’| j}|d u r0tj}|r0t d¡ d}|tj	ksL|tj
krt|rtddlm} |dk rpt d |¡¡ d}ddlm} ||ƒ |  |¡ z"d V  W t | tjjƒsÐ|  |¡ nt | tjjƒsÎ|  |¡ 0 d S )	NaO  You are exporting the model to ONNX while in training mode with 'train' parameter not specified. The model will default to inference mode export. If you wish to export a training amenable ONNX model, specify training=TrainingMode.TRAINING or training=TrainingMode.PRESERVE (to preserve the original model state) in torch.onnx.export().Fr   ©Ú_export_onnx_opset_versioné   zµYou are exporting the model in training mode with onnx opset version {}. Opset versions lower than opset 12 will not be able to export nodes such as Dropout and BatchNorm correctly.T)Ú_set_training_mode)Ú
isinstanceÚtorchÚjitÚScriptFunctionÚtrainingr   ÚEVALÚwarningsÚwarnZTRAININGZPRESERVEÚtorch.onnx.symbolic_helperr   Úformatr   Ztrain)ÚmodelÚmodeZis_originally_trainingZis_export_trainingr   r   r   r   r   Úselect_model_mode_for_export'   s.    
þ
ÿr(   Tc                 C   s¤   |d u rt jjrtj}ntj}|d ur0t d¡ |
d urBt d¡ |d urTt d¡ |d urft d¡ |d urxt d¡ t| |||||||||	||||||d� d S )Nz­'enable_onnx_checker' is deprecated and ignored. It will be removed in the next PyTorch release. To proceed despite ONNX checker failures, catch torch.onnx.ONNXCheckerError.ú_'_retain_param_name' is deprecated and ignored. It will be removed in the next PyTorch release.z‚`strip_doc_string' is deprecated and ignored. Will be removed in next PyTorch release. It's combined with `verbose' argument now. zU`example_outputs' is deprecated and ignored. Will be removed in next PyTorch release.zî`use_external_data_format' is deprecated and ignored. Will be removed in next PyTorch release. The code will work as it is False if models are not larger than 2GB, Otherwise set to False because of size limits imposed by Protocol Buffers.)Úoperator_export_typeÚopset_versionÚdo_constant_foldingÚexample_outputsÚdynamic_axesÚkeep_initializers_as_inputsÚcustom_opsetsÚuse_external_data_format)	r   ÚonnxÚPYTORCH_ONNX_CAFFE2_BUNDLEr   ÚONNX_ATEN_FALLBACKÚONNXr"   r#   Ú_export)r&   ÚargsÚfÚexport_paramsÚverboser    Úinput_namesÚoutput_namesr*   r+   Ú_retain_param_namer,   r-   Zstrip_doc_stringr.   r/   r0   Zenable_onnx_checkerr1   r   r   r   ÚexportM   s(    




ür>   c                 C   sH   |   ¡ dkrdS |  ¡  ¡ }| t ¡ ¡r.dS | tt ¡ ƒ¡rDdS d S )Nzprim::ConstantFT)ÚkindÚoutputÚtypeÚisSubtypeOfr   Ú	ofTensorsr	   ZofTensor)ÚnodeÚoutput_typer   r   r   Ú_is_constant_tensor_listr   s    rF   c                 C   s˜   |  ¡ D ]Š}| ¡ D ]}t| |ƒ qt|ƒrg }| ¡  ¡ D ]&}|  |¡}| ¡  |¡ | 	|¡ q<|  
d|¡ |¡ ¡  t ¡ ¡}| ¡  |¡ qd S )Nzprim::ListConstruct)ÚnodesÚblocksÚ_split_tensor_list_constantsrF   r@   ÚtoIValueZinsertConstantrD   Z
moveBeforeÚappendÚcreateÚinsertBeforeÚsetTyper   rC   ZreplaceAllUsesWith)ÚgÚblockrD   ZsubblockÚinputsÚvalÚinputÚlcr   r   r   rI   }   s    
ÿýrI   c           
      C   s@  t j | ¡ t j | ¡ t j | ¡ t j | ¡ |du rDt j | ¡ t| | ƒ t j | ¡ t j | ¡ t j 	| ¡ t j | ¡ t j 
| d¡ t j | ¡ t j | ¡ ddlm}m}	 t j 
| d¡ t j | ¡ t j | |¡ t j | ¡ t j | ¡ t j | ¡ t j | ¡ t j | ¡ |tjk�r^t jjj ¡  t j | |¡ t j | |¡ t j dd| ¡ t j | ¡ |�r¤|d u �r~g n|}|d u �r�i n|}t j | ||¡ t j | |¡} t j | ¡ t j  | d|	¡ t j | ¡ t j !| |	|¡ t j | ¡ t j "| ¡ t j | ¡ t j #| ¡} t j | ¡ |�r<t j $| ||	¡ | S )NFTr   )Ú_onnx_shape_inferencer   z…
        graph(%Pi):
            %Pq = quantized::nhwc2nchw(%Pi)
            %Pr = quantized::nchw2nhwc(%Pq)
            return (%Pr)z-
        graph(%Ri):
            return (%Ri))%r   Ú_CZ_jit_pass_inlineZ_jit_pass_inline_fork_waitZ_jit_pass_lintZ_jit_pass_lower_all_tuplesZ_jit_pass_constant_propagationrI   Z_jit_pass_dceZ&_jit_pass_canonicalize_graph_fuser_opsZ_jit_pass_peepholeZ_jit_pass_fuse_addmmr$   rU   r   Z*_jit_pass_onnx_remove_inplace_ops_for_onnxZ_jit_pass_onnx_preprocessZ#_jit_pass_prepare_division_for_onnxZ_jit_pass_onnx_remove_printZ _jit_pass_onnx_preprocess_caffe2r   r4   r2   Zsymbolic_helperZ_quantized_opsÚclearZ'_jit_pass_onnx_unpack_quantized_weightsZ+_jit_pass_onnx_quantization_insert_permutesZ,_jit_pass_custom_pattern_based_rewrite_graphZ_jit_pass_erase_number_typesZ&_jit_pass_onnx_set_dynamic_input_shapeZ_jit_pass_onnxZ#_jit_pass_onnx_scalar_type_analysisZ_jit_pass_onnx_peepholeÚ4_jit_pass_dce_allow_deleting_nodes_with_side_effectsZ_jit_pass_canonicalizeÚ)_jit_pass_onnx_graph_shape_type_inference)
Úgraphr*   Ú_disable_torch_constant_propÚfixed_batch_sizeÚparams_dictr.   r;   ÚmodulerU   r   r   r   r   Ú_optimize_graph�   sb    
ú	r_   c                 C   sr   t | d | d ƒD ]Z\}}t|tƒrLt| ¡ ƒt| ¡ ƒkrld}t |¡ qt|tƒr||krd}t |¡ qd S )Nr   é   aQ  We detected that you are modifying a dictionary that is an input to your model. Note that dictionaries are allowed as inputs in ONNX but they should be handled with care. Usages of dictionaries is not recommended, and should not be used except for configuration use. Also note that the order and values of the keys must remain the same. zvThe model seems to have string inputs/outputs. Note that strings will not appear as inputs/outputs of the ONNX graph. )Úzipr   ÚdictÚlistÚkeysr"   r#   Ústr)Zinput_statesrS   Ztraced_inputÚwarningr   r   r   Úwarn_on_static_input_changeô   s    

rg   c                 C   s,   ||j ur(|du r$t d | | ¡¡ d}|S )NTz•`{}' can be set to True only when 'operator_export_type' is `ONNX`. Since 'operator_export_type' is not set to 'ONNX', `{}` argument will be ignored.F)r5   r"   r#   r%   )Zarg_nameÚ	arg_valuer*   r   r   r   Ú_resolve_args_by_export_type  s    
þri   c                 C   sH   |dk r| du rt  d¡ dS | d u r*dn| }| d u rD|tju rDd}|S )Né	   Fa  Setting 'keep_initializers_as_inputs=False' for opset version8 or lower would lead to an invalid ONNX graph. Therefore, 'keep_initializers_as_inputs=False' is ignored during export.Exported model will have initialiers as graph inputs (compliant  to ONNX IR v3).T)r"   r#   r   r5   )r/   r*   r+   Úval_keep_init_as_ipr   r   r   Ú_decide_keep_init_as_input  s    
rl   c                 C   s   t d| |ƒS )NÚadd_node_names)ri   )rm   r*   r   r   r   Ú_decide_add_node_names/  s    rn   c                 C   s0   t d| |ƒ} | r,|d ur,|tjur,t d¡ | S )Nr,   aâ  It is recommended that constant folding be turned off ('do_constant_folding=False') when exporting the model in training-amenable mode, i.e. with 'training=TrainingMode.TRAIN' or 'training=TrainingMode.PRESERVE' (when model is in training mode). Otherwise, some learnable model parameters may not translate correctly in the exported ONNX model because constant folding mutates model parameters. Please consider turning off constant folding or setting the training=TrainingMode.EVAL.)ri   r   r!   r"   r#   )r,   r*   r    r   r   r   Ú_decide_constant_folding3  s    
ro   c                 C   s:   t d| |ƒ}|d u s|du r,t|tƒr,|}ntƒ }||fS )Nr1   T)ri   r   re   )r1   r*   r8   Úval_use_external_data_formatÚmodel_file_locationr   r   r   Ú_decide_external_data_format?  s    þrr   c           
   
   C   s>  dd l }z®| | j¡}t|j ¡ ƒ}t|d tƒr²|d }t|ƒd d… }t|ƒ}||d … D ]J}||v rz| 	|| ¡ q^|j| }|j
|ju rœ| 	d ¡ q^| 	|j
¡ q^t|ƒ}|W S  ttfyÚ   t d¡ | Y S  t� yú   t d¡ | Y S  t�y8 }	 z&t d |	jd ¡¡ |W  Y d }	~	S d }	~	0 0 d S )Nr   éÿÿÿÿzModel has no forward functionzNo input argsz!Skipping _decide_input_format
 {})ÚinspectÚ	signatureÚforwardrc   Ú
parametersrd   r   rb   ÚlenrK   ÚdefaultÚemptyÚtupleÚAttributeErrorÚ
ValueErrorr"   r#   Ú
IndexErrorÚ	Exceptionr%   r7   )
r&   r7   rt   ÚsigZordered_list_keysZ	args_dictZn_nonkeywordZoptional_argÚparamÚer   r   r   Ú_decide_input_formatM  s4    


rƒ   c                 C   sT   t |tjƒr|f}tjj| |dddd�\}}}t|ƒ t||i d�}|rP||fS |S )NFT©ÚstrictZ_force_outplaceZ_return_inputs_states)r]   )r   r   ÚTensorr   Ú_get_trace_graphrg   r_   )Úfuncr7   r*   Zreturn_outsÚtrace_graphÚ	torch_outÚinputs_statesr   r   r   Ú_tracen  s    ÿrŒ   c                 C   sP   t | ƒ ¡ }tjj| |dddd�\}}}t|ƒ |t | ƒ ¡ krHtdƒ‚||fS )NFTr„   zXstate_dict changed after running the tracer; something weird is happening in your model!)r   rd   r   r   r‡   rg   ÚRuntimeError)r&   r7   Zorig_state_dict_keysr‰   rŠ   r‹   r   r   r   Ú_trace_and_get_graph_from_model}  s    ÿrŽ   c                 C   sZ   g }t |  ¡ |ƒD ]B\}}dt| ¡ ƒv rJtj |¡\}}| t|ƒ¡ q| d¡ q|S )NZPackedParamsr`   )	ra   rQ   re   rA   r   r   Ú_flattenrK   rx   )Úmethod_graphÚargs_paramsÚparam_count_listZinput_Zarg_params_Úin_varsÚ_r   r   r   Ú_get_param_count_listŽ  s    r•   c              
   C   sÌ  d }t | tjjƒrÒz„| jj}tj |¡ tjj| j	dd�}tj 
|¡\}}| d¡j}t|ƒt|ƒ }t||ƒ}	tj |¡\}
}t|t|
ƒ|	ddƒ}W n. tyÄ } ztdƒ|‚W Y d }~n
d }~0 0 ||||fS t | tjjƒ�r6d}tj t|ƒ¡\}
}| j}tj |¡ t||ƒ}	t|t|
ƒ|	ddƒ}|||d fS t| |ƒ\}}t| ƒ}t| ¡ ƒ}t| ¡ ƒ}t|ƒt|ƒ }t| ¡ ƒ}t|ƒD ]&\}}||k�rˆ| |||  ¡ �qˆtj |¡ |||d fS d S )NT)ZpreserveParametersrv   Fz('forward' method must be a script methodr   )r   r   r   ÚScriptModulerv   rZ   rV   Z$_jit_pass_onnx_function_substitutionZ_freeze_moduleZ_cZ_jit_onnx_list_model_parametersZ_get_methodr{   r•   r�   r
   r|   r�   r   rŽ   r   rc   ÚvaluesrQ   rx   rd   Ú	enumerateÚsetDebugName)r&   r7   rŠ   rZ   Z	freezed_mr^   Úparamsr�   r‘   r’   r“   r”   r‚   Zin_descZ
state_dictZgraph_inputsZuser_input_numÚparam_namesÚiÚinpr   r   r   Ú_create_jit_graph™  sL    
ÿ 
ÿ
rž   c                 C   s<   dd„ |   ¡ D ƒ}|t|ƒt|ƒ d … }tt||ƒƒ}|S )Nc                 S   s   g | ]}|  ¡ ‘qS r   ©Ú	debugName)Ú.0rR   r   r   r   Ú
<listcomp>Ã  ó    z)_get_named_param_dict.<locals>.<listcomp>)rQ   rx   rb   ra   )rZ   rš   Zinput_and_param_namesr›   Ú_params_dictr   r   r   Ú_get_named_param_dictÂ  s    r¥   c                 C   sp   t  |¡}i }|r4t|d tƒr4|d }|d d… }| |i |¤Ž}t|tjtttfƒr\|f}t|t	ƒrl|g}|S )Nrs   )
ÚcopyÚdeepcopyr   rb   r   r†   ÚintÚfloatÚboolrc   )r&   r7   Z
input_argsZinput_kwargsr-   r   r   r   Ú_get_example_outputsÈ  s    

r«   c              
   C   sˆ  ddl m} t|tjtttfƒr&|f}t| |ƒ\}}}}t	||ƒ}t
||||	||||d�}ddl m} t| tjjƒs‚t| tjjƒrè|du r–t| |ƒ}n*t|tjtttfƒr°|f}t|tƒrÀ|g}tj t|ƒ¡\}}tj ||||¡ n<tj |¡\}}t|ƒt|ƒ tdd„ | ¡ D ƒƒk�s$J ‚|du�rxt|tƒ�sNt|tƒ�sN|g}n|}tj t|ƒ¡\}}tj ||||¡ t|||ƒ tj |¡\}}t|ƒt|ƒ tdd„ | ¡ D ƒƒk�sÀJ ‚t	||ƒ}|
du �sà|
tjk�rîtj ||¡}|�r|tjjv �rtj |||¡}tj  |¡ |�r4tj !|||¡ tj "||¡}|d	k �rXtj #|¡ |�rft$|ƒ tj %|¡}tj &|¡ |||fS )
a  Converts model into an ONNX graph.

    Returns:
      graph (torch._C.Graph): A TorchScript IR Graph with ONNX nodes.
      params_dict (Dict[str, torch.Tensor]): Dict from input param name to param value.
      torch_out (Union[NoneType, torch.Tensor, Tuple[torch.Tensor], List[torch.Tensor]]):
        The output tensors resulting from the trace of ``model``.
        If ``model`` is a :class:`torch.jit.ScriptModule` or :class:`torch.jit.ScriptFunction`,
        this will be None, since we are not doing any tracing.
    r   r   )r[   r\   r]   r.   r;   r^   ©rU   Nc                 s   s   | ]
}d V  qdS ©r`   Nr   ©r¡   r”   r   r   r   Ú	<genexpr>  r£   z"_model_to_graph.<locals>.<genexpr>c                 s   s   | ]
}d V  qdS r­   r   r®   r   r   r   r¯     r£   rj   )'r$   r   r   r   r†   r¨   r©   rª   rž   r¥   r_   rU   r   r–   r   r«   rc   r�   r{   rV   Z"_jit_pass_onnx_assign_output_shapeZ_jit_flattenrx   ÚsumrQ   Ú_set_input_and_output_namesr   r!   Z_jit_pass_onnx_eval_peepholer2   Zconstant_folding_opset_versionsZ_jit_pass_onnx_constant_foldrX   rY   Z%_jit_pass_onnx_eliminate_unused_itemsZ,_jit_pass_onnx_cast_all_constant_to_floatingÚprintZ%_jit_pass_filter_non_tensor_argumentsZ#_jit_decay_packed_param_input_types)r&   r7   r:   r;   r<   r*   r-   r,   r[   r\   r    r.   r   rZ   rš   rŠ   r^   r]   rU   Zout_varsÚdescZflatten_argsr”   Zoutput_wrappedZoutput_tensorsZout_descr   r   r   Ú_model_to_graph×  sd    
ü
,
,

ÿ
r´   c                 C   sP   |d urt  d¡ |d ur$t  d¡ t| |||||||||	|
|||||||d�S )NzN'f' is deprecated and ignored. It will be removed in the next PyTorch release.r)   )r,   rm   r/   r0   r.   )r"   r#   Ú_export_to_pretty_string)r&   r7   r8   r9   r:   r    r;   r<   r*   Úexport_typer-   Úgoogle_printerr+   r=   r/   r0   rm   r,   r.   r   r   r   Úexport_to_pretty_string7  s    

úr¸   c                 C   sî   ddl m}m} ddl m} |d u r(|}|d u r4i }||ƒ ||ƒ ddl m} ||ƒ t| |ƒ�x t|||ƒ}t||ƒ}t|||ƒ}t	| |ƒ}t
| ||||||
||||d�\}}}| ||d|||||¡W  d   ƒ S 1 sà0    Y  d S )Nr   ©Ú_default_onnx_opset_versionÚ_set_opset_version©Ú_set_operator_export_type©Ú_set_onnx_shape_inference©r\   r    r.   F)r$   rº   r»   r½   r¿   r(   rl   rn   ro   rƒ   r´   Z_pretty_print_onnx)r&   r7   r8   r9   r:   r    r;   r<   r*   r¶   r-   r·   r+   r,   r/   r\   r0   rm   Úonnx_shape_inferencer.   rº   r»   r½   r¿   rk   Úval_add_node_namesÚval_do_constant_foldingrZ   r]   rŠ   r   r   r   rµ   K  s8    þ


ü
þrµ   c	                 C   s¶   ddl m}	m}
 |du r|	}|
|ƒ tj}t| |ƒ�2 t| |ƒ}t| |||||ƒ\}}}W d  ƒ n1 sl0    Y  tƒ }| 	¡ D ](}| 
¡  d¡d dvr„| | 
¡ ¡ q„||fS )a3  
    This diagnostic tool runs your model with operator_export_type set to
    OperatorExportTypes.ONNX_FALLTHROUGH once in order to get a list of
    all the ops that are not supported/implemented by the current exporter

    operator_export_type is set to OperatorExportTypes.ONNX_FALLTHROUGH by default
        OperatorExportTypes.ONNX_FALLTHROUGH: If an op is not supported
        in ONNX, fall through and export the operator as is, as a custom
        ONNX op. Using this mode, the op can be exported and implemented by
        the user for their runtime backend.
        Example graph::

            graph(%0 : Float(2, 3, 4, strides=[12, 4, 1], requires_grad=0, device=cpu)):
                %6 : Long(requires_grad=0, device=cpu) = prim::Constant[value={0}]()
                %4 : None = prim::Constant()
                %5 : Float(2, 3, 4, strides=[12, 4, 1], requires_grad=0, device=cpu) = aten::cumsum(%0, %6, %4) # main.py:6:0
                return (%5)

        is exported as::

            graph(%0 : Float(2, 3, 4, strides=[12, 4, 1], requires_grad=0, device=cpu)):
                %6 : Long(requires_grad=0, device=cpu) = prim::Constant[value={0}]()
                %4 : None = prim::Constant()
                %5 : Float(2, 3, 4, strides=[12, 4, 1], requires_grad=0, device=cpu) = aten::cumsum(%0, %6, %4) # main.py:6:0
                return (%5)

        In the above example, aten::cumsum in not implemented in opset 9, hence exporter falls
        through and provides a list of unsupported ops, the result being:
            Unsupported ops : [aten:cumsum]
    r   r¹   Nú:)r2   Úprim)r$   rº   r»   r   ÚONNX_FALLTHROUGHr(   rƒ   r´   rc   rG   r?   ÚsplitrK   )r&   r7   r8   r:   r    r;   r<   r+   r.   rº   r»   r*   rZ   r]   rŠ   Zunsupported_opsrD   r   r   r   Ú_find_missing_ops_onnx_exportm  s     

ÿ(rÈ   c           -      C   sô  t | tjjƒrtdƒ‚tdu s"J ‚da�z¶ddlm} ||ƒ ddlm}m	} ddlm
} |d u rf|}|s€tjjrztj}ntj}||ƒ ||ƒ t| |ƒ��  t|||ƒ}t||ƒ}t|||ƒ}t|||ƒ\}}t| |ƒ}|d u ræi }t|| ||ƒ t| ||||||
||||d�\}}}|	tju} |d u �r0i }|�r^| |||| || |||||¡\}!}"}n&| i ||d|| |||||¡\}!}"}|	tjk�ràt|"ƒdk�s¢J ‚tj |d	¡�}#|# |!¡ W d   ƒ n1 �sÒ0    Y  �n€|	tjtj fv �rrdd l!}$|	tj k�r|$j"n|$j#}%|$j$|d
|%d��<}&|& %t&|!¡ |" '¡ D ]\}'}(|& %|'|(¡ �q8W d   ƒ n1 �sf0    Y  nî|	tj(k�rXdd l)})|)j* +|¡�r¨|)j* ,|¡�s²J ‚n
|) -|¡ |)j* .|t&¡}*tj |*d	¡�}#|# |!¡ W d   ƒ n1 �sð0    Y  |" '¡ D ]R\}'}(|)j* .||'¡}+tj |+d	¡�}#|# |(¡ W d   ƒ n1 �sH0    Y  �qnt/dƒ‚|tju �r®|�s®zt0|!ƒ W n. t/�y¬ }, zt1|,ƒ‚W Y d },~,n
d },~,0 0 W d   ƒ n1 �sÄ0    Y  W t�sÚJ ‚dant�sêJ ‚da0 |S )Nz«torch.nn.DataParallel is not supported by ONNX exporter, please use 'attribute' module to unwrap model from torch.nn.DataParallel. Try torch.onnx.export(model.module, ...)FTr   r¾   r¹   r¼   rÀ   ÚwbÚw)ÚcompressionzUnknown export type)2r   r   ÚnnZDataParallelr}   r   r$   r¿   rº   r»   r½   r2   r3   r   r4   r5   r(   rl   rn   ro   rr   rƒ   Ú_validate_dynamic_axesr´   r   ÚPROTOBUF_FILEZ_export_onnxrx   ZserializationZ_open_file_likeÚwriteZZIP_ARCHIVEZCOMPRESSED_ZIP_ARCHIVEÚzipfileÚZIP_DEFLATEDÚ
ZIP_STOREDÚZipFileÚwritestrr   ÚitemsZ	DIRECTORYÚosÚpathÚexistsÚisdirÚmakedirsÚjoinr�   r   r   )-r&   r7   r8   r9   r:   r    r;   r<   r*   r¶   r-   r+   r,   r.   r/   r\   r0   rm   r1   rÁ   r¿   rº   r»   r½   rk   rÂ   rÃ   rp   rq   rZ   r]   rŠ   Zdefer_weight_exportÚprotoZ
export_mapZopened_filerÐ   rË   ÚzÚkÚvrÖ   Zmodel_proto_fileZweight_proto_filer‚   r   r   r   r6   Ÿ  s¶    þ
þ

ûÿ	


ý

ý
.ÿ
þ2
*0@
ÿ
r6   c                 C   s4   dd„ }|t |  ¡ ƒ|dƒ |t |  ¡ ƒ|dƒ d S )Nc                 S   sf   |d u rd S t |ƒt | ƒkr8td|t |ƒ|t | ƒf ƒ‚t|| ƒD ]\}}| ¡ |krB| |¡ qBd S )Nz<number of %s names provided (%d) exceeded number of %ss (%d))rx   r�   ra   r    r™   )Z	node_listÚ	name_listZ
descriptorÚnamerD   r   r   r   Ú	set_names  s    ÿÿz._set_input_and_output_names.<locals>.set_namesrS   r@   )rc   rQ   Úoutputs)rZ   r;   r<   râ   r   r   r   r±     s    
r±   z^(.+)_([ifstgz])$c              
   C   sT   z|| g|¢R Ž W S  t yN } z$d |jd |¡f|_‚ W Y d}~n
d}~0 0 dS )z\
    This trampoline function gets invoked for every symbolic method
    call from C++.
    z!{} (occurred when translating {})r   N)Ú	TypeErrorr%   r7   )rO   Úop_nameÚsymbolic_fnr7   r‚   r   r   r   Ú_run_symbolic_method+  s
    rç   c                 C   s,   t | tƒs(t | tjƒs(t | tjjƒr(dS dS )NTF)r   r   r   r†   ÚcollectionsÚabcÚIterable)Úvaluer   r   r   Ú_is_onnx_list:  s    

ÿþrì   c                 C   sš   t  |¡}|du r td |¡ƒ‚| d¡| d¡ }}t|ƒrF|d7 }|r†t|tjƒr†| 	¡ dkrjt
dƒ‚t|ƒ}t|tƒr‚d}nd}t| |d	 ƒ||ƒS )
z8 initializes the right attribute based on type of value Nz\Invalid attribute specifier '{}' names  must be suffixed with type, e.g. 'dim_i' or 'dims_i'r`   é   Úsz Should not pass tensor attributer8   rœ   r”   )Úattr_patternÚmatchr~   r%   Úgrouprì   r   r   r†   Únumelr}   Ú_scalarr©   Úgetattr)rD   Úkeyrë   ÚatenÚmrá   r?   r   r   r   Ú_add_attributeB  s&    
ÿþ
rø   c                 C   s   |   ¡ dksJ ‚| d S )z,Convert a scalar tensor into a Python value.r`   r   )rò   )Úxr   r   r   ró   Y  s    ró   c                 O   sx   d|v rd}|}n$|  dd¡}|r&dnd}|d | }|  |||¡}t| ¡ ƒD ]"\}	}
|	dkrbqPt||	|
|d� qP|S )Nú::Frö   r2   Úinplace©rö   )ÚpoprL   ÚsortedrÕ   rø   )rO   Úopnamerã   r7   Úkwargsrö   Ú	ns_opnameÚnsÚnrÞ   rß   r   r   r   Ú_newNode_  s    r  c           	         s¶   |  dd¡}tdd„ | ¡ D ƒƒ}‡fdd„‰ t‡ fdd„|D ƒƒ}ˆ tˆ||g|¢R i |¤Ž¡}dd	lm} |r�dd
lm} t	j
 |t|¡ |dkr | ¡ S tdd„ | ¡ D ƒƒS )a¯  
    Create an ONNX operator "opname", taking "args" as inputs and attributes
    "kwargs"; returning the node representing the single output of this operator
    (see the `outputs` keyword argument for multi-return nodes).

    The set of operators and the inputs/attributes they take
    is documented at https://github.com/onnx/onnx/blob/master/docs/Operators.md

    This function is monkey-patched onto Graph.

    Args:
        opname (string): The ONNX operator name, e.g., `Abs` or `Add`.
        args (Node...): The inputs to the operator; usually provided
            as arguments to the `symbolic` definition.
        kwargs: The attributes of the ONNX operator, with keys named
            according to the following convention: `alpha_f` indicates
            the `alpha` attribute with type `f`.  The valid type specifiers are
            `f` (float), `i` (int), `s` (string) or `t` (Tensor).  An attribute
            specified with type float accepts either a single float, or a
            list of floats (e.g., you would say `dims_i` for a `dims` attribute
            that takes a list of integers).
        outputs (int, optional):  The number of outputs this operator returns;
            by default an operator is assumed to return a single output.
            If `outputs` is greater than one, this functions returns a tuple
            of output `Node`, representing each output of the ONNX operator
            in positional.
    rã   r`   c                 s   s"   | ]\}}|d ur||fV  qd S r   r   )r¡   rÞ   rß   r   r   r   r¯   �  r£   z_graph_op.<locals>.<genexpr>c                    s0   | d u r| S t | tjjƒr| S ˆ jd| d�S d S )NÚConstant)Úvalue_z)r   r   rV   ÚValueÚop)Úarg)rO   r   r   Úconst_if_tensor’  s
    z"_graph_op.<locals>.const_if_tensorc                 3   s   | ]}ˆ |ƒV  qd S r   r   )r¡   r	  )r
  r   r   r¯   š  r£   r   r¬   r   c                 s   s   | ]
}|V  qd S r   r   ©r¡   Úor   r   r   r¯   ¤  r£   )rý   rb   rÕ   rc   Z
insertNoder  r$   rU   r   r   rV   Ú(_jit_pass_onnx_node_shape_type_inferencer¤   r@   r{   rã   )	rO   rÿ   Zraw_argsr   rã   r7   r  rU   r+   r   )r
  rO   r   Ú	_graph_opp  s     r  c           
      O   s¨   d|v rd}|}n$|  dd¡}|r&dnd}|d | }|  |t|ƒ¡}t| ¡ ƒD ]"\}}	|dkrdqRt|||	|d� qRtt| ¡ ƒƒdkr’| ¡ S t	dd	„ | ¡ D ƒƒS )
Nrú   Frö   r2   rû   rü   r`   c                 s   s   | ]
}|V  qd S r   r   r  r   r   r   r¯   ·  r£   z_block_op.<locals>.<genexpr>)
rý   ZaddNoderc   rþ   rÕ   rø   rx   rã   r@   r{   )
Úbrÿ   r7   r   rö   r  r  r  rÞ   rß   r   r   r   Ú	_block_op§  s    r  c                 C   s   |   ¡ S r   )ÚaddBlock)rD   r   r   r   Ú
_add_blockº  s    r  c                 C   s   |   ¡ S r   )ZaddInputToBlock)rP   r   r   r   Ú_add_input_to_block¾  s    r  c                 C   s   |   |¡}|S r   )ZregisterOutput)rP   rë   Z
new_outputr   r   r   Ú_add_output_to_blockÂ  s    
r  c                 C   s<   dd l m  m} | || |¡s.|tjkr.d S | || |¡S )Nr   )Útorch.onnx.symbolic_registryr2   Úsymbolic_registryÚis_registered_opr   rÆ   Zget_registered_op)Údomainrå   r+   r*   Úsym_registryr   r   r   Ú_find_symbolic_in_registryÐ  s
    
r  c           (   
      s  �zœdd l ‰ddlm} dd lm  m} | d|¡ |tjkr`|dkr`dd l	‰ˆjj
 d|¡ ˆ  ¡  d¡r€ˆ  ¡ d d… }nˆ  ¡ }| d¡\}	}
|	d	krø|
d
kr¸ˆj |ˆ |¡W S ‡ fdd„ˆ  ¡ D ƒ}| j|
g|¢R i |¤dˆ  ¡ i¤ŽW S �n¤|	dk�rÎ| |
d|¡}|tjk}|tjk}|�s6|�sz|�rz‡ fdd„ˆ  ¡ D ƒ}ˆ  ¡ }||d< t| |
g|¢R ddi|¤ŽW S d}t||
||ƒ}|d u �rœW d S ‡ fdd„ˆ  ¡ D ƒ}|| g|¢R i |¤ŽW S �nÎ|	dk�rÄ|
dk�rÚˆ  ¡ �sÚˆ  d¡dk�r| jdˆ d d�W S ˆ  d¡dk�r4| jdˆ d d�W S ˆ  ¡  ¡  t ¡ ¡�sdˆ  ¡  ¡  t ¡ ¡�r¦ˆ  ¡   ¡ }t!|ƒ�r’ˆ "‡fdd„|D ƒ¡ng }| jd|d�W S ˆ  ¡  ¡  ¡ dk�rÂW d S t#d $ˆ  d¡¡ƒ‚�qœˆ  ¡ �s|
dk�s|
dk�s|
dk�rW d S |
d k�r.ˆ  ¡  ¡  ¡ dk�r.W d S |
d!k�sB|
d"k�rT|
d"k�o^|d  %¡  ¡ d#k}d$}|�r>|d  %¡ d  &¡ }t'|t(ƒ�r’t)|ƒnt*|ƒ}|�r¤dnd%}t(ˆ  +¡ ƒ| }d}ˆj ,|||||¡}t(ˆ  -¡ ƒ}t(| -¡ ƒ}g }t.t!|ƒƒD ]>}|| |v�rt#d&||  d' ƒ‚|||  }| /|¡ �qø|W S | j|
g|¢R dˆ  ¡ iŽ}ˆ  ¡ d%k�rt|d  %¡ n| %¡ } ˆ  +¡ D ]–}!|  0¡ }"t1|! 2¡ ƒD ]f\}#}$|#dk�rÎ|#t!|ƒk �rÎ|$ 3||#  ¡ ¡ |#dk�rœ|#d% t!|ƒk �rœ|$ 3||#d%   ¡ ¡ �qœˆj ,|!|"|||¡ �q„ˆj 4| |¡}dd(lm5}% |%�rLˆj 6| t7|¡ |W S nnd)|
 }&d}t||&||ƒ}|d u �r~W d S ‡ fd*d„ˆ  ¡ D ƒ}|
d+k�rªˆ g|¢R }|| g|¢R i |¤ŽW S nØ|	d,k�r.d}|tjk�râd}t||
||ƒ}|d u �r W d S ‡ fd-d„ˆ  ¡ D ƒ}|| g|¢R i |¤ŽW S | 8|	|¡�rŒ|	}t||
||ƒ}|d u �r^W d S ‡ fd.d„ˆ  ¡ D ƒ}|| g|¢R i |¤ŽW S t#d/ $|	|
¡ƒ‚W nd t#�yÆ   |tj9k�rÀY d S ‚ Y n> t:�y }' z$d0 $|'j;d |
¡f|'_;‚ W Y d }'~'n
d }'~'0 0 d S )1Nr   r   Ú rj   Zcaffe2r”   rs   rú   r2   ZPlaceholderc                    s(   i | ] }|d  ˆ   |¡d  ˆ | “qS ©r”   r   ©ÚkindOf©r¡   rÞ   ©r  r   r   Ú
<dictcomp>ô  r£   z*_run_symbolic_function.<locals>.<dictcomp>rã   rö   c                    s(   i | ] }|d  ˆ   |¡d  ˆ | “qS r  r  r  r   r   r   r!  ý  r£   Tc                    s   i | ]}|ˆ | “qS r   r   r  r   r   r   r!    r£   rÅ   r  rë   Út)Úvalue_trî   )Zvalue_sc                    s   g | ]}ˆ   |¡‘qS r   )Útensor)r¡   rß   )r   r   r   r¢     r£   z*_run_symbolic_function.<locals>.<listcomp>ZDeviceObjTypez9Unsupported prim::Constant kind: `{}`. Send a bug report.ZListConstructZ
ListUnpackZUninitializedZdeviceZLoopÚIfzonnx::ConstantFr`   zThe sub block ATen output z is not in env.r¬   Zprim_c                    s   i | ]}|ˆ | “qS r   r   r  r   r   r   r!  u  r£   ZPythonOpZ	quantizedc                    s   i | ]}|ˆ | “qS r   r   r  r   r   r   r!  �  r£   c                    s   i | ]}|ˆ | “qS r   r   r  r   r   r   r!  Š  r£   z³ONNX export failed on an operator with unrecognized namespace {}::{}. If you are trying to export a custom operator, make sure you registered it with the right domain and version.z#{} 
(Occurred when translating {}).)<r   r$   r   r  r2   r  Zregister_versionr   r4   Ztorch.onnx.symbolic_caffe2Zsymbolic_caffe2Zregister_quantized_opsr?   ÚendswithrÇ   rV   Z'_jit_onnx_convert_pattern_from_subblockZattributeNamesr  ZoutputsSizer  Z	ONNX_ATENÚ	_graph_atr  Z
mustBeNoner  r@   rA   rB   r   ZofIntsZofFloatsrJ   rx   Ústackr�   r%   rD   Útolistr   rc   Úallrª   rH   Z_jit_pass_onnx_blockrã   ÚrangerK   r  r˜   rQ   rN   Z%_jit_pass_fixup_onnx_controlflow_noderU   r  r¤   Zis_registered_versionrÆ   rä   r7   )(rO   rP   r  rQ   Úenvr*   r+   r  Z
ns_op_namer  rå   ÚattrsZis_exportable_aten_opZis_onnx_aten_exportZis_aten_fallback_exportrã   r  ræ   Úvalsrë   Z	static_ifZis_sub_blockZ
input_flagZconst_valueZ	block_idxZ	current_bZif_output_listZcurrent_b_listZfinal_b_listÚidxZonnx_bZnew_op_outputsÚnew_noder  Z	new_blockrœ   Zb_inrU   Úsymbolic_namer‚   r   )r  r   r   Ú_run_symbolic_functionÙ  sü    *




0&ÿ
( ÿ"ÿÿ




þ
r2  c                 O   s   | j dg|¢R d|i|¤ŽS )NZATenZ
operator_s)r  )rO   rÿ   r7   r   r   r   r   r'  œ  s    r'  c                 O   s0  t |tjƒsJ ‚|d usJ ‚d}|d u sB|dksBt|ƒtdgƒkrLdg}d}| ¡ }|dkrhtj|Ž }n€|dkr|tj|Ž }nl|dkr�tj|Ž }nX|dkr¤tj	|Ž }nD|d	kr¸tj
|Ž }n0|d
krÌtj|Ž }n|dkràtj|Ž }ntdƒ‚| |¡ |�r| jdg|¢R d|i|¤ŽS | jdg|¢R d|i|¤ŽS )NFr   r`   TÚcharÚshortr¨   ÚlongZhalfr©   ÚdoublezfUnknown type, type should be one of the following strings: char, short, int, long, half, float, doubler  r  r#  )r   ÚnumbersÚNumberÚsetÚlowerr   Z
CharTensorZShortTensorZ	IntTensorZ
LongTensorZ
HalfTensorZFloatTensorZDoubleTensorr}   Zfill_r  )rO   rë   ÚdimsrA   r7   r   Zisscalarr$  r   r   r   Ú_graph_constant¥  s4    "
r<  c                 C   s   |   |¡}t| |ƒ|ƒS )z�
    Accessor for attributes of a node which is polymorphic over
    return type.

    NB: This is monkey-patched onto Node.
    )r  rô   )ÚselfrÞ   Úselr   r   r   Ú_node_getitemÈ  s    
r?  c                 C   sT   t t d| ¡ƒstd | ¡ƒ‚|  d¡\}}g d¢}||v rLtd | |¡ƒ‚||fS )Nz+^[a-zA-Z0-9-_]*::[a-zA-Z-_]+[a-zA-Z0-9-_]*$zðFailed to register operator {}.                            The symbolic name must match the format Domain::Name,                            and should start with a letter and contain only                            alphanumerical charactersrú   )r2   rö   rÅ   zGFailed to register operator {}. The domain {} is already a used domain.)rª   Úrerð   r�   r%   rÇ   )r1  r  rå   Zunaccepted_domain_namesr   r   r   Úget_ns_op_name_from_custom_opÓ  s    üÿrA  c           	      C   sZ   t | ƒ\}}dd lm  m} ddlm}m} ||g D ]}||kr8| ||||¡ q8d S ©Nr   )Ú_onnx_stable_opsetsÚ_onnx_main_opset)rA  r  r2   r  r$   rC  rD  Zregister_op)	r1  ræ   r+   r  rå   r  rC  rD  Úversionr   r   r   Úregister_custom_op_symbolicæ  s    rF  c                 C   sX   t | ƒ\}}dd lm  m} ddlm}m} ||g D ]}||kr8| |||¡ q8d S rB  )rA  r  r2   r  r$   rC  rD  Zunregister_op)r1  r+   r  rå   r  rC  rD  rE  r   r   r   Úunregister_custom_op_symbolicð  s    rG  c           
      C   s0  t | ƒdkrd S t|dƒrj|d u s.t |ƒdkrBdd„ |j ¡ D ƒ}|d u sVt |ƒdkrjdd„ |j ¡ D ƒ}t|prg |pxg  ƒ}|  ¡ D ]¤\}}||vr¦t d 	|¡¡ t
|tƒr†t d 	|¡¡ i }t|ƒD ]T\}}	t
|	tƒsætdƒ‚|	|v �rt d	 	|	|¡¡ qÌt|ƒd
 t|d ƒ ||	< qÌ|| |< q†d S )Nr   rZ   c                 S   s   g | ]}|  ¡ ‘qS r   rŸ   )r¡   rù   r   r   r   r¢     r£   z*_validate_dynamic_axes.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r   rŸ   )r¡   Úyr   r   r   r¢     r£   zAProvided key {} for dynamic axes is not a valid input/output namez�No names were found for specified dynamic axes of provided input.Automatically generated names will be applied to each dynamic axes of input {}z3The type of axis index is expected to be an integerz:Duplicate dynamic axis index {} was provided for input {}.Z_dynamic_axes_r`   )rx   ÚhasattrrZ   rQ   rã   r9  rÕ   r"   r#   r%   r   rc   r˜   r¨   r}   re   )
r.   r&   r;   r<   Zvalid_namesrõ   rë   Z
value_dictrœ   rù   r   r   r   rÍ   û  s2    

ÿ

ÿrÍ   )TFNNNNNNTNNNNNNN)FFNNNN)F)ZÚ__doc__r   Z	torch.jitZtorch.autogradZtorch.serializationr@  rè   Ú
contextlibr¦   r7  r"   Z
torch._sixr   r   Z
torch.onnxr   r   r   r   Ztorch._Cr   r	   r
   r   Útypingr   r   r   r   r   r   r   r¤   Úcontextmanagerr(   r>   rF   rI   r_   rg   ri   rl   rn   ro   rr   rƒ   rŒ   rŽ   r•   rž   r¥   r«   r5   r´   rÎ   r¸   rµ   r!   rÈ   r6   r±   Úcompilerï   rç   rì   rø   ró   r  r  r  r  r  r  r  r2  r'  r<  r?  rA  rF  rG  rÍ   rV   ZGraphr  ÚatZBlockZconstantÚNodeÚ__getitem__r   r   r   r   Ú<module>   sÔ   
%      û
%  ÿ
e!
)û
`û
ú
"ÿ
2ú
{
7	 D	#
$



