o
    ĎiS                  	   @   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 d dl	Z	d dl
mZ d dl	mZ d dl	mZ d d	lmZ d d
lmZ d dlmZ d dlmZ dedefddZG dd dejZ		ddeeeef dededejfddZdS )    N)OrderedDict)getitem)Path)Union)
ModelProto)fx)nn)get_converter)	OnnxGraph)	ValueType)safe_shape_inferencemodelreturnc                 C   sB   | j j}dd |D }| j jD ]}|j|v r|||j  q| S )Nc                 S   s   i | ]}|j |qS  name).0	one_inputr   r   P/home/jeff/fluffinator/venv/lib/python3.10/site-packages/onnx2torch/converter.py
<dictcomp>   s    z3_remove_initializers_from_input.<locals>.<dictcomp>)graphinputinitializerr   remove)r   graph_inputsgraph_inputs_mappingr   r   r   r   _remove_initializers_from_input   s   
r   c                   @   s0   e Zd ZdZdedejddfddZdd	 ZdS )
InitializersContainerz2Module for storing initializers in torch fx graph.r   r   r   Nc                 C   s   |  || d S N)register_buffer)selfr   r   r   r   r   add_initializer    s   z%InitializersContainer.add_initializerc                 O   s   t d)Nz.Got unexpected "forward" on constant container)RuntimeError)r    argskwargsr   r   r   forward#   s   zInitializersContainer.forward)	__name__
__module____qualname____doc__strtorchTensorr!   r%   r   r   r   r   r      s    r   Fonnx_model_or_pathsave_input_namesattach_onnx_mappingc                     s8  t | }|jdk rtdt|}dd |jD }t|j t }t	 }t
 }|d| i t jdD ]"\}}	|rL|	 sItd|	 d|	}
nd	| }
|j|
d
|	< q7 j D ]\}	}||j }t|j|j|d}|| \}}|rt|d| ||	| g }|jD ]} |}|tjkr||  q|tjkrӈ |\}}|j }t |j!dkr|j!"|}|j#t$||fd}||	d < || q|tj%krt&dd |' D }d| }|vr|(| j)| *  |+d| |< ||  q|tj,kr|d qt-d| di }d|v rX|"d}t.t/0|j1j23 }||t | }|d| ||d }}|4dd t5||D  |j6|	t.||d|	< q_ fdd j!D }t7t89|}fdd|D }t |dkr|d }|:| |;  tj<||d}|S )aA  Convert model from onnx to PyTorch.

    This function build torch.fx GraphModule from onnx ModelProto using operations from the converter registry.
    The registered operation can be found in onnx2torch/node_converters.

    Usage example:

        from onnx2torch import convert
        torch_module = convert('path/to/onnx_model.onnx')


    Parameters
    ----------
    onnx_model_or_path : Union[str, Path, ModelProto]
        Onnx ModelProto or model path to convert.
    save_input_names : bool
        Whether to use original onnx inputs names as fx graph placeholders names or to use generated names (input_n).
        False by default.
    attach_onnx_mapping : bool
        Whether to attach info about mapping to original onnx tensors names.

    Returns
    -------
    fx.GraphModule
        PyTorch GraphModule

       z4Onnx IR is too old (minimal supported version is 3).c                 S   s   i | ]}|j |jqS r   )domainversion)r   opsetid_protor   r   r   r   N       zconvert.<locals>.<dictcomp>initializers   zInput name "z:" cannot be used as name of placeholder in fx.GraphModule.input_r   )r1   operation_typer2   onnx_mapping)r#   _split_outputc                 s   s    | ]}d V  qdS )r6   Nr   )r   _r   r   r   	<genexpr>   s    zconvert.<locals>.<genexpr>onnx_initializer_zinitializers.Nz!Got unexpected input value type ()c                 S   s   i | ]\}}|d ur||qS r   r   )r   r   valuer   r   r   r      s    )module_namer#   r$   c                    s   g | ]	}  |d  qS )r   )value_as_node_output)r   
value_name)
onnx_graphr   r   
<listcomp>   s    zconvert.<locals>.<listcomp>c                    s   g | ]} |j  qS r   )unique_name)r   	onnx_node)torch_nodesr   r   rD      r4   r   )rootr   )=r   
ir_versionNotImplementedErrorr   opset_importr
   r   r   Graphr   r   Module
add_module	enumerateinput_valuesisidentifier
ValueErrorplaceholdernodesitemsr1   r	   r8   setattrinputs
value_typer   GRAPH_INPUTappendNODE_OUTPUTrA   rE   lenoutput_valuesindexcall_functionr   GRAPH_INITIALIZERsumbuffersr!   r5   to_torchget_attrEMPTYr"   tupleinspect	signaturer%   
parameterskeysupdatezipcall_modulelistr   fromkeysoutputlintGraphModule) r-   r.   r/   
onnx_modelrK   torch_graphtorch_initializerstorch_modulesinput_valuer   placeholder_namerF   r2   	convertertorch_moduler9   r#   rB   rX   onnx_input_noder;   torch_input_noder^   len_torch_initializerstorch_buffer_namer$   first_skipped_argforward_argskwargs_valuesonnx_output_nodestorch_output_nodestorch_modelr   )rC   rG   r   convert'   s   !













r   )FF)rg   collectionsr   operatorr   pathlibr   typingr   r+   onnx.onnx_ml_pb2r   r   r   onnx2torch.node_convertersr	   onnx2torch.onnx_graphr
   r   %onnx2torch.utils.safe_shape_inferencer   r   rM   r   r*   boolrr   r   r   r   r   r   <module>   s4    