a
    ÞñhÛ  ã                   @   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m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ad	d
„ Zejdd„ ƒZdWdd„Zdd„ Zdd„ ZdXdd„Zdd„ Zdd„ Z dd„ Z!dd„ Z"dd„ Z#d d!„ Z$dYd"d#„Z%d$d%„ Z&d&d'„ Z'dddej(ddddddddfd(d)„Z)ddddddddej*ddddddddfd*d+„Z+dddddej(ej*dddddddddfd,d-„Z,dej-ddddfd.d/„Z.ddddddej*ddddddddddddddfd0d1„Z/d2d3„ Z0e 1d4¡Z2d5d6„ Z3d7d8„ Z4d9d:„ Z5d;d<„ Z6d=d>„ Z7d?d@„ Z8dAdB„ Z9dCdD„ Z:dEdF„ Z;dGdH„ Z<dIdJ„ Z=ej(fdKdL„Z>dMdN„ Z?dOdP„ Z@dQdR„ ZAdSdT„ ZBdUdV„ ZCe8ejDjE_Fe?ejDjE_Ge9ejDjH_Fe@ejDjE_IeAejDjJ_KdS )ZzÐ
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)Úcontainer_abcs)Ústring_classes)Ú_unique_state_dict)ÚONNX_ARCHIVE_MODEL_PROTO_NAMEÚExportTypesÚOperatorExportTypesÚTrainingMode)ÚListTypeÚOptionalTypeÚ"_propagate_and_assign_input_shapesÚ_check_onnx_protoFc                   C   s   t S ©N)Ú__IN_ONNX_EXPORT© r   r   úP/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/onnx/utils.pyÚ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 asDropout and BatchNorm correctly.T)Ú_set_training_mode)Ú
isinstanceÚtorchÚjitÚScriptFunctionÚtrainingr   ÚEVALÚwarningsÚwarnZTRAININGÚPRESERVEÚtorch.onnx.symbolic_helperr   Úformatr   Ztrain)ÚmodelÚmodeÚis_originally_trainingZis_export_trainingr   r   r   r   r   Úselect_model_mode_for_export    s.    
þ
ÿr$   Tc                 C   s‚   |s|	r2|
d u sJ ‚||	A s J ‚|r*t jnt j}
n|
d u rPtjjrJt j}
nt j}
t| ||||||||
||||||||||d� d S )N)Úoperator_export_typeÚopset_versionÚ_retain_param_nameÚdo_constant_foldingÚexample_outputsÚstrip_doc_stringÚdynamic_axesÚkeep_initializers_as_inputsÚcustom_opsetsÚenable_onnx_checkerÚuse_external_data_format)	r   ÚATENÚRAWr   ÚonnxÚPYTORCH_ONNX_CAFFE2_BUNDLEÚONNX_ATEN_FALLBACKÚONNXÚ_export)r!   ÚargsÚfÚexport_paramsÚverboser   Úinput_namesÚoutput_namesÚatenÚexport_raw_irr%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r   r   r   ÚexportF   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_list^   s    rG   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_constantsrG   rA   ÚtoIValueZinsertConstantrE   Z
moveBeforeÚappendÚcreateÚinsertBeforeÚsetTyper	   rD   ZreplaceAllUsesWith)ÚgÚblockrE   ZsubblockÚinputsÚvalÚinputÚlcr   r   r   rJ   i   s    
ÿýrJ   c           
      C   sz  t j | ¡ t j | ¡ t j | ¡ |rBt j | ¡ t j | ¡ nt j | ¡ |du rbt j | ¡ t	| | ƒ t j 
| ¡ t j | ¡ t j | ¡ t j | ¡ t j | d¡ t j | ¡ t j | ¡ |tjk�r"t j | d¡ t j | ¡ t j | ¡ t j | ¡ t j | ¡ t j | ¡ t j | ¡ t j | ¡ |tjk�rvt jjj ¡  t j | |¡ t j | |¡ t j dd| ¡ t j | ¡ ddlm} |�rÈ|d u �r¢g n|}|d u �r´i n|}t j  | ||¡ t j !| |¡} t j | ¡ t j "| ¡ t j | ¡ ddlm#}	 t j $| |	|¡ t j | ¡ t j %| ¡ t j | ¡ t j &| ¡} t j | ¡ ddlm}m#}	 |�rvt j '| |	¡ | S )	NFTz•
            graph(%Pi):
                %Pq = quantized::nhwc2nchw(%Pi)
                %Pr = quantized::nchw2nhwc(%Pq)
                return (%Pr)z5
            graph(%Ri):
                return (%Ri)r   ©Ú_onnx_shape_inferencer   )rW   r   )(r   Ú_CZ_jit_pass_inlineZ_jit_pass_inline_fork_waitZ_jit_pass_lintZ_jit_pass_lower_all_tuplesZ*_jit_pass_onnx_remove_inplace_ops_for_onnxZ_jit_pass_remove_inplace_opsZ_jit_pass_constant_propagationrJ   Z_jit_pass_dceZ&_jit_pass_canonicalize_graph_fuser_opsZ_jit_pass_peepholeZ_jit_pass_fuse_addmmr   r1   Z_jit_pass_onnx_preprocessZ+_jit_pass_onnx_prepare_inplace_ops_for_onnxZ#_jit_pass_prepare_division_for_onnxZ_jit_pass_onnx_remove_printZ _jit_pass_onnx_preprocess_caffe2r4   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_typesr   rW   Z&_jit_pass_onnx_set_dynamic_input_shapeZ_jit_pass_onnxZ#_jit_pass_onnx_scalar_type_analysisr   Z_jit_pass_onnx_peepholeÚ4_jit_pass_dce_allow_deleting_nodes_with_side_effectsZ_jit_pass_canonicalizeZ)_jit_pass_onnx_graph_shape_type_inference)
Úgraphr%   Ú_disable_torch_constant_propÚfixed_batch_sizeÚparams_dictÚuse_new_jit_passesr+   r;   rW   r   r   r   r   Ú_optimize_graph{   sn    
ú	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   é   aR  We detected that you are modifying a dictionnary 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_statesrT   Ztraced_inputÚwarningr   r   r   Úwarn_on_static_input_changeé   s    

rh   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    
þrj   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    
rm   c                 C   s   t d| |ƒS )NÚadd_node_names)rj   )rn   r%   r   r   r   Ú_decide_add_node_names$  s    ro   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.)rj   r   r   r   r   )r(   r%   r   r   r   r   Ú_decide_constant_folding(  s    
rp   c                 C   s,   t d| |ƒ}|rt|tƒr|ntƒ }||fS )Nr/   )rj   r   rf   )r/   r%   r8   Úval_use_external_data_formatÚmodel_file_locationr   r   r   Ú_decide_external_data_format4  s    þrs   c                 C   sP   t |tjƒr|f}tjj| |dddd�\}}}t|ƒ t||ƒ}|rL||fS |S )NFT©ÚstrictZ_force_outplaceZ_return_inputs_states)r   r   ÚTensorr   Ú_get_trace_graphrh   r`   )Úfuncr7   r%   Zreturn_outsÚtrace_graphÚ	torch_outÚinputs_statesr   r   r   Ú_trace@  s    ÿ
r|   c                 C   sP   t | ƒ ¡ }tjj| |dddd�\}}}t|ƒ |t | ƒ ¡ krHtdƒ‚||fS )NFTrt   zXstate_dict changed after running the tracer; something weird is happening in your model!)r   re   r   r   rw   rh   ÚRuntimeError)r!   r7   Zorig_state_dict_keysry   rz   r{   r   r   r   Ú_trace_and_get_graph_from_modelO  s    ÿr~   c              
   C   s°  d }t | tjjƒrÌzˆ| jj}tj |¡ |sBtj || j	¡\}}n(tj 
| j	¡}| d¡j}| d¡ g }tj t|ƒt|ƒ ¡\}	}
t|t|	ƒddƒ}W n. tyÈ } ztdƒ|‚W Y d }~n
d }~0 0 nÚt | tjjƒ�rd}tj t|ƒ¡\}	}
| j}tj |¡ t|t|	ƒddƒ}nŒt| |ƒ\}}t| ƒ}t| ¡ ƒ}|�ršt| ¡ ƒ}t|ƒt|ƒ }t| ¡ ƒ}t|ƒD ]&\}}||k�rr| |||  ¡ �qrtj |¡ |||fS )NÚforwardr   Fz('forward' method must be a script methodr   )r   r   r   ÚScriptModuler   r[   rX   Z$_jit_pass_onnx_function_substitutionZ_jit_pass_lower_graphZ_cZ_freeze_moduleZ_get_methodZ
eraseInputÚ_flattenÚtupler   ÚAttributeErrorr}   r   r~   r   rd   ÚvaluesrR   Úlenre   Ú	enumerateÚsetDebugName)r!   r7   r'   r_   rz   r[   Zmethod_graphÚparamsZ	freezed_mZin_varsZin_descÚeZ
state_dictZgraph_inputsZuser_input_numÚparam_namesÚiÚinpr   r   r   Ú_create_jit_graph`  sJ    
ÿ"ÿ
r�   c              
   C   sT  ddl m} t|tjƒr|f}t|tjƒr0|g}t| |||ƒ\}}}dd„ | ¡ D ƒ}|t|ƒt|ƒ d … }tt	||ƒƒ}t
|||	|
||||d�}ddl m} t| tjjƒs¼t| tjjƒrð|d usÌJ dƒ‚tj t|ƒ¡\}}tj |||¡ |d u�rtj |¡\}}tj |||¡ t|||ƒ tj |¡\}}t|ƒt|ƒ tdd	„ | ¡ D ƒƒk�sbJ ‚d
d„ | ¡ D ƒ}|t|ƒt|ƒ d … }tt	||ƒƒ}|d u �sÂ|tjk�sÂ|tjk�rÐt�sÐtj ||¡}|�r |tjjv �r tj |||¡}tj |¡ tj ||¡}|dk �r$tj  |¡ |�r2t!|ƒ tj "|¡}tj #|¡ |||fS )Nr   r   c                 S   s   g | ]}|  ¡ ‘qS r   ©Ú	debugName©Ú.0rS   r   r   r   Ú
<listcomp>�  ó    z#_model_to_graph.<locals>.<listcomp>)r\   r]   r^   r_   r+   r;   rV   zQexample_outputs must be provided when exporting a ScriptModule or ScriptFunction.c                 s   s   | ]
}d V  qdS )ra   Nr   )r‘   Ú_r   r   r   Ú	<genexpr>·  r“   z"_model_to_graph.<locals>.<genexpr>c                 S   s   g | ]}|  ¡ ‘qS r   rŽ   r�   r   r   r   r’   ¹  r“   rk   )$r   r   r   r   rv   r�   rR   r…   rc   rb   r`   rW   r   r€   r   r�   r‚   rX   Z"_jit_pass_onnx_assign_output_shapeZ_jit_flattenÚ_set_input_and_output_namesÚsumr   r   r   r#   Z_jit_pass_onnx_eval_peepholer2   Zconstant_folding_opset_versionsZ_jit_pass_onnx_constant_foldrZ   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_   r+   r   r[   rˆ   rz   Zinput_and_param_namesrŠ   r^   rW   Zout_varsr”   Zoutput_tensorsZflatten_argsr   r   r   Ú_model_to_graph‰  s^    þ
ü
,(
ÿ
r™   c                 C   sl   |s|	r2|
d u sJ ‚||	A s J ‚|r*t jnt j}
n|
d u r@t j}
t| ||||||||
|||||||||d�S )N)r(   rn   r,   r-   )r   r0   r1   r5   Ú_export_to_pretty_string)r!   r7   r8   r9   r:   r   r;   r<   r=   r>   r%   Úexport_typer)   Úgoogle_printerr&   r'   r,   r-   rn   r(   r   r   r   Úexport_to_pretty_stringÕ  s    ùr�   c                 C   sÐ   ddl m}m} ddl m} |d u r(|}|d u r4i }||ƒ ||ƒ t| |ƒ�n 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)r]   r   F)
r   rŸ   r    r¢   r$   rm   ro   rp   r™   Z_pretty_print_onnx)r!   r7   r8   r9   r:   r   r;   r<   r%   r›   r)   rœ   r&   r'   r(   r,   r]   r-   rn   rŸ   r    r¢   rl   Úval_add_node_namesÚval_do_constant_foldingr[   r^   rz   r   r   r   rš   ì  s2    þ

ü
þrš   c	                 C   s¬   ddl m}	m}
 |du r|	}|
|ƒ tj}t| |ƒ�( t| |||||ƒ\}}}W d  ƒ n1 sb0    Y  tƒ }| ¡ D ](}| 	¡  
d¡d dvrz| | 	¡ ¡ qz||fS )aÿ  
    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:12, 3:4, 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:12, 3:4, 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:12, 3:4, 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:12, 3:4, 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™   rd   rH   r@   ÚsplitrL   )r!   r7   r8   r:   r   r;   r<   r&   r+   rŸ   r    r%   r[   r^   rz   Zunsupported_opsrE   r   r   r   Ú_find_missing_ops_onnx_export
  s     
ÿ(r©   c           0      C   s¸  t | tjjƒrtdƒ‚tdu s"J ‚da�zzd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|||ƒ\}} |d u rÜi }t|| ||ƒ t| ||||||
||||||d�\}!}"}#|	tju}$|d u �r*i }|�rT|! |"|||$||||||| ¡\}%}&n"|! i ||d||||||| ¡\}%}&|�r–|tju �r–|�s–t|%ƒ |	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 �r„dd l!}(|	tj k�r|(j"n|(j#})|(j$|d
|)d��<}*|* %t&|%¡ |& '¡ D ]\}+},|* %|+|,¡ �qJW d   ƒ n1 �sx0    Y  nî|	tj(k�rjd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 �sZ0    Y  �qnt/dƒ‚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   )Ú_set_onnx_shape_inferencerž   r¡   )r]   r   r_   r+   ÚwbÚw)ÚcompressionzUnknown export type)0r   r   ÚnnZDataParallelÚ
ValueErrorr   r   rª   rŸ   r    r¢   r2   r3   r   r4   r5   r$   rm   ro   rp   rs   Ú_validate_dynamic_axesr™   r   ÚPROTOBUF_FILEZ_export_onnxr   r…   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}   )0r!   r7   r8   r9   r:   r   r;   r<   r%   r›   r)   r&   r'   r(   r*   r+   r,   r]   r-   rn   r.   r/   Zonnx_shape_inferencer_   rª   rŸ   r    r¢   rl   r£   r¤   rq   rr   r[   r^   rz   Zdefer_weight_exportÚprotoZ
export_mapZopened_filer³   r­   ÚzÚkÚvr¹   Zmodel_proto_fileZweight_proto_filer   r   r   r6   C  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))r…   r}   rb   r�   r‡   )Z	node_listÚ	name_listZ
descriptorÚnamerE   r   r   r   Ú	set_names½  s    ÿÿz._set_input_and_output_names.<locals>.set_namesrT   rA   )rd   rR   Úoutputs)r[   r;   r<   rÅ   r   r   r   r–   ¼  s    
r–   z^(.+)_([ifstgz])$c              
   C   sL   z
||Ž W S  t yF } 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   )Ú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ƒr&dS dS )NTF)r   r   r   rv   r   Ú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'ra   é   Úsz Should not pass tensor attributer8   r‹   r”   )Úattr_patternÚmatchÚ
IndexErrorr    ÚgrouprÍ   r   r   rv   Únumelr¯   Ú_scalarÚfloatÚgetattr)rE   ÚkeyrÌ   r=   ÚmrÄ   r@   r   r   r   Ú_add_attributeä  s&    
ÿþ
rÚ   c                 C   s   |   ¡ dksJ ‚| d S )z,Convert a scalar tensor into a Python value.ra   r   )rÔ   )Úxr   r   r   rÕ   û  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=   )ÚpoprM   Úsortedr¸   rÚ   )rP   Ú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
 ||¡ |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.

    Arguments:
        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Æ   ra   c                 s   s"   | ]\}}|d ur||fV  qd S r   r   )r‘   rÁ   rÂ   r   r   r   r•   2  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   rX   ÚValueÚop)Úarg)rP   r   r   Úconst_if_tensor4  s
    z"_graph_op.<locals>.const_if_tensorc                 3   s   | ]}ˆ |ƒV  qd S r   r   )r‘   rë   )rì   r   r   r•   <  r“   r   rV   r   c                 s   s   | ]
}|V  qd S r   r   ©r‘   Úor   r   r   r•   F  r“   )rß   rc   r¸   rd   Z
insertNoderæ   r   rW   r   r   rX   Ú(_jit_pass_onnx_node_shape_type_inferencerA   r‚   rÆ   )	rP   rá   Zraw_argsrâ   rÆ   r7   rå   rW   r&   r   )rì   rP   r   Ú	_graph_op  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Þ   ra   c                 s   s   | ]
}|V  qd S r   r   rí   r   r   r   r•   Y  r“   z_block_op.<locals>.<genexpr>)
rß   ZaddNoderd   rà   r¸   rÚ   r…   rÆ   rA   r‚   )
Úbrá   r7   râ   r=   rã   rä   rå   rÁ   rÂ   r   r   r   Ú	_block_opI  s    rò   c                 C   s   |   ¡ S r   )ÚaddBlock)rE   r   r   r   Ú
_add_block\  s    rô   c                 C   s   |   ¡ S r   )ZaddInputToBlock)rQ   r   r   r   Ú_add_input_to_block`  s    rõ   c                 C   s   |   |¡}|S r   )ZregisterOutput)rQ   rÌ   Z
new_outputr   r   r   Ú_add_output_to_blockd  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_registryr  s
    
rü   c              
      sf  �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¤W d S |d
k�rx| |	d|¡}
|tjk}|tjk}|sà|
�s$|�r$‡ fdd„ˆ  ¡ D ƒ}ˆ  ¡ }||d< t| |	g|¢R d
di|¤ŽW S d}t||	||ƒ}|d u �rFW 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�rÞ| jdˆ d d�W S ˆ  ¡  ¡  t ¡ ¡�sˆ  ¡  ¡  t ¡ ¡�rPˆ  ¡  ¡ }t|ƒ�r<ˆ  ‡fdd„|D ƒ¡ng }| jd|d�W S ˆ  ¡  ¡  ¡ dk�rlW d S t!d "ˆ  d¡¡ƒ‚�qúˆ  ¡ �s¢|	dk�s¢|	dk�r¨W d S |	dk�rÎˆ  ¡  ¡  ¡ dk�rÎW d S |	dk�sâ|	dk�rÈ| j|	g|¢R dˆ  ¡ iŽ}ˆ  ¡ d k�r|d  #¡ n| #¡ }ˆ  $¡ D ]j}| %¡ }t&| '¡ ƒD ]<\}}|dk�r@|d  t|ƒk �r@| (||d    ¡ ¡ �q@ˆj) *||||¡ �q(ˆj) +||¡}dd!lm,} |�rÂˆj) -||¡ |W S d"|	 }d}t||||ƒ}|d u �ròW d S ‡ fd#d„ˆ  ¡ D ƒ}|| 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 | .||¡�rê|}t||	||ƒ}|d u �r¼W d S ‡ fd&d„ˆ  ¡ D ƒ}|| g|¢R i |¤ŽW S t!d' "||	¡ƒ‚W nd t!�y$   |tj/k�rY d S ‚ Y n> t0�y` } z$d( "|j1d |	¡f|_1‚ W Y d }~n
d }~0 0 d S ))Nr   r   Ú rk   Zcaffe2r”   éÿÿÿÿrÜ   r2   r=   c                    s(   i | ] }|d  ˆ   |¡d  ˆ | “qS )r”   r   )ÚkindOf©r‘   rÁ   ©rå   r   r   Ú
<dictcomp>›  r“   z*_run_symbolic_function.<locals>.<dictcomp>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deviceZLoopÚIfra   rV   Zprim_c                    s   i | ]}|ˆ | “qS r   r   r   r  r   r   r  Ö  r“   Z	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 {}).)2r   r   r   r÷   r2   rø   Zregister_versionr   r4   Ztorch.onnx.symbolic_caffe2Zsymbolic_caffe2Zregister_quantized_opsr@   Úendswithr¨   rù   Z	ONNX_ATENZattributeNamesZoutputsSizeÚ	_graph_atrü   Z
mustBeNonerÿ   rê   rA   rB   rC   r	   ZofIntsZofFloatsrK   r…   Ústackr}   r    rE   rI   ró   r†   rR   rO   rX   Z_jit_pass_onnx_blockZ%_jit_pass_fixup_onnx_controlflow_noderW   rï   Zis_registered_versionr§   rÇ   r7   )rP   rå   rR   Úenvr%   r&   rû   Z
ns_op_namerä   rÈ   Zis_exportable_aten_opZis_onnx_aten_exportZis_aten_fallback_exportÚattrsrÆ   rú   rÉ   ÚvalsrÌ   Znew_op_outputsÚnew_noderñ   Z	new_blockr‹   Zb_inrW   Úsymbolic_namer‰   r   )rå   r   r   Ú_run_symbolic_function{  sÂ    




0&ÿ
 "ÿ



þ
r  c                 O   s   | j dg|¢R d|i|¤ŽS )NZATenZ
operator_s)rê   )rP   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   ra   TÚcharÚshortÚintÚ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ê   )rP   rÌ   ÚdimsrB   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   s�   t t d| ¡ƒstd | ¡ƒ‚|  d¡\}}g d¢}||v rLtd | |¡ƒ‚dd lm  m} ddl	m
} |D ]}||krn| ||||¡ qnd 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   )Ú_onnx_stable_opsets)ÚboolÚrerÑ   r}   r    r¨   r÷   r2   rø   r   r  Zregister_op)	r  rÉ   r&   rä   rÈ   Zunaccepted_domain_namesrû   r  Úversionr   r   r   Úregister_custom_op_symbolic.  s    üÿr"  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   r[   c                 S   s   g | ]}|  ¡ ‘qS r   rŽ   )r‘   rÛ   r   r   r   r’   I  r“   z*_validate_dynamic_axes.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r   rŽ   )r‘   Úyr   r   r   r’   K  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_ra   )r…   Úhasattrr[   rR   rÆ   r  r¸   r   r   r    r   rd   r†   r  r¯   rf   )
r+   r!   r;   r<   Zvalid_namesrØ   rÌ   Z
value_dictr‹   rÛ   r   r   r   r°   B  s2    

ÿ

ÿr°   )TFNNNFFNNTTNTNNNTF)FFNFNN)F)LÚ__doc__r   Z	torch.jitZtorch.autogradZtorch.serializationr   Z
torch._sixr   Ú
contextlibr  r   r   r   Z
torch.onnxr   r   r   r   Ztorch._Cr	   r
   r   r   r   r   Úcontextmanagerr$   r?   rG   rJ   r`   rh   rj   rm   ro   rp   rs   r|   r~   r�   r5   r™   r±   r�   rš   r   r©   r6   r–   ÚcompilerÐ   rÊ   rÍ   rÚ   rÕ   ræ   rð   rò   rô   rõ   rö   rü   r  r  r  r  r"  r°   rX   ZGraphrê   ÚatZBlockZconstantÚNodeÚ__getitem__r   r   r   r   Ú<module>   sÆ   
%      û
  ÿ
n
)ù
Lú
û
ÿ
9ù
y
7	 	$



