U
    Mhq                    @  s  U d dl m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mZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZ d dlZd dlZd dl m!Z" d dl#m$  m%Z& d dl'm(Z( d dl)m*Z*m+Z+ d dl,m-Z- d d	l.m/Z/m0Z0m1Z1m2Z3 erPd dl4Z4d dl5Z5d dl6Z6d d
l7m1Z8 d dl.m9Z9 n(zd dl.m9Z9 W n e:k
rv   Y nX dZ;de<d< dZ=dZ>dZ?e@eAZBe-jCZCejDG dd dZEG dd dZFG dd dZGG dd deGZHejIdd ZJeG dd deZKG dd dZLG d d! d!ZMG d"d# d#ZNG d$d% d%ZOG d&d' d'ejPZQG d(d) d)ZRG d*d+ d+eSZTG d,d- d-eSZUG d.d/ d/eSZVe*jWdd0d1d2ZXe*jWdd0d3d4d%d5d6d7ZYdd8d9d:d;d<d=ZZd>dd%dd#d/d-dd+d7dgZ[dS )?    )annotationsN)defaultdict)AnyCallableDictFinalListMappingOptionalProtocolruntime_checkableSequenceSetTupleTYPE_CHECKINGTypeVarUnion)Selffake_tensor)	_beartype
io_adapter)infra)decomposition_tablepatcherregistrationserializationr   )diagnostics   z
Final[int]_DEFAULT_OPSET_VERSIONz)https://github.com/pytorch/pytorch/issueszreport_dynamo_export.sarifl        c                   @  s&   e Zd ZU dZded< dZded< dS )ONNXFakeContextaV  A dataclass used to store context for model export using FakeTensor.

    This dataclass stores the FakeTensorMode instance used to convert
    real tensors and model parameters into fake tensors. This :attr:`ONNXFakeContext.fake_mode` is
    reused internally during tracing of a :class:`torch.nn.Module` into a FX :class:`GraphModule`.
    zfake_tensor.FakeTensorMode	fake_modeNz7Optional[Tuple[Union[str, io.BytesIO, Dict[str, Any]]]]state_dict_paths)__name__
__module____qualname____doc____annotations__r#    r)   r)   O/var/www/html/venv/lib/python3.8/site-packages/torch/onnx/_internal/exporter.pyr!   _   s   
r!   c                	   @  s   e Zd ZdZddddZeddddZd	d
ddZej	ddddddZ
ej	d$dddddddddZej	d%dddddddZej	d&ddddddd Zej	d!dd"d#ZdS )'OnnxRegistrya  Registry for ONNX functions.

    The registry maintains a mapping from qualified names to symbolic functions under a
    fixed opset version. It supports registering custom onnx-script functions and for
    dispatcher to dispatch calls to the appropriate function.

    Nonereturnc                 C  s@   t t| _ddlm} t| _td| j d | 	|j
 dS )zInitializes the registryr   r   z7torch.onnx.dynamo_export only implements opset version ze for now. If you need to use a different opset version, please register them with register_custom_op.N)r   list	_registry"onnxscript.function_libs.torch_libr   r    _opset_versionwarningswarn _initiate_registry_from_torchlibZdefault_registry)selfr   r)   r)   r*   __init__x   s    zOnnxRegistry.__init__intc                 C  s   | j S )zThe ONNX opset version the exporter should target. Defaults to the latest
        supported ONNX opset version: 18. The default version will increment over time as
        ONNX continues to evolve.)r2   r6   r)   r)   r*   opset_version   s    zOnnxRegistry.opset_versionztorchlib_registry.Registry)torchlib_registryc                 C  s~   |  D ]p\}}tj|}|jD ]&}tj|| ddd}| || q"|jD ]&}tj|| ddd}| || qPqdS )zPopulates the registry with ATen functions from torchlib.

        Args:
            torchlib_registry: The torchlib registry to use for populating the registry.
        FZonnx_functionZop_full_nameZ	is_custom
is_complexTN)	itemsr   OpNameZfrom_qualified_nameZ	overloadsONNXFunctionqualified_name	_registercomplex)r6   r;   Z	aten_nameZaten_overloads_funcinternal_name_instanceZoverload_funcsymbolic_functionZcomplex_funcr)   r)   r*   r5      s$    

z-OnnxRegistry._initiate_registry_from_torchlibzregistration.OpNamezregistration.ONNXFunction)internal_qualified_namerE   r.   c                 C  s   | j | | dS )zRegisters a ONNXFunction to an operator.

        Args:
            internal_qualified_name: The qualified name of the operator to register: OpName.
            symbolic_function: The ONNXFunction to register.
        N)r0   append)r6   rF   rE   r)   r)   r*   rB      s    zOnnxRegistry._registerNFzCUnion[('onnxscript.OnnxFunction', 'onnxscript.TracedOnnxFunction')]strzOptional[str]bool)function	namespaceop_nameoverloadr=   r.   c                 C  s8   t jj|||d}t j|| d|d}| || dS )aO  Registers a custom operator: torch.ops.<namespace>.<op_name>.<overload>.

        Args:
            function: The onnx-sctip function to register.
            namespace: The namespace of the operator to register.
            op_name: The name of the operator to register.
            overload: The overload of the operator to register. If it's default overload,
                leave it to None.
            is_complex: Whether the function is a function that handles complex valued inputs.

        Raises:
            ValueError: If the name is not in the form of 'namespace::op'.
        rK   rL   rM   Tr<   N)r   r?   from_name_partsr@   rA   rB   )r6   rJ   rK   rL   rM   r=   rD   rE   r)   r)   r*   register_op   s      zOnnxRegistry.register_opz)Optional[List[registration.ONNXFunction]])rK   rL   rM   r.   c                 C  s   t jj|||d}| j|S )an  Returns a list of ONNXFunctions for the given op: torch.ops.<namespace>.<op_name>.<overload>.

        The list is ordered by the time of registration. The custom operators should be
        in the second half of the list.

        Args:
            namespace: The namespace of the operator to get.
            op_name: The name of the operator to get.
            overload: The overload of the operator to get. If it's default overload,
                leave it to None.
        Returns:
            A list of ONNXFunctions corresponding to the given name, or None if
            the name is not in the registry.
        rN   )r   r?   rO   r0   get)r6   rK   rL   rM   rD   r)   r)   r*   get_op_functions   s      zOnnxRegistry.get_op_functionsc                 C  s   | j |||d}|dk	S )a  Returns whether the given op is registered: torch.ops.<namespace>.<op_name>.<overload>.

        Args:
            namespace: The namespace of the operator to check.
            op_name: The name of the operator to check.
            overload: The overload of the operator to check. If it's default overload,
                leave it to None.

        Returns:
            True if the given op is registered, otherwise False.
        rN   N)rR   )r6   rK   rL   rM   Z	functionsr)   r)   r*   is_registered_op   s      zOnnxRegistry.is_registered_opzSet[str]c                 C  s   dd | j  D S )z1Returns the set of all registered function names.c                 S  s   h | ]}|  qS r)   )rA   ).0Zop_name_classr)   r)   r*   	<setcomp>  s    z3OnnxRegistry._all_registered_ops.<locals>.<setcomp>)r0   keysr9   r)   r)   r*   _all_registered_ops  s    z OnnxRegistry._all_registered_ops)NF)N)N)r$   r%   r&   r'   r7   propertyr:   r5   r   beartyperB   rP   rR   rS   rW   r)   r)   r)   r*   r+   o   s&        r+   c                   @  st   e Zd ZU dZdZded< dZded< ded< dZded	< dZd
ed< e	j
dddddddddd
ddddZdS )ExportOptionsa  Options to influence the TorchDynamo ONNX exporter.

    Attributes:
        dynamic_shapes: Shape information hint for input/output tensors.
            When ``None``, the exporter determines the most compatible setting.
            When ``True``, all input shapes are considered dynamic.
            When ``False``, all input shapes are considered static.
        op_level_debug: Whether to export the model with op-level debug information
        diagnostic_options: The diagnostic options for the exporter.
        fake_context: The fake context used for symbolic tracing.
        onnx_registry: The ONNX registry used to register ATen operators to ONNX functions.
    NzOptional[bool]dynamic_shapesop_level_debugDiagnosticOptionsdiagnostic_optionsOptional[ONNXFakeContext]fake_contextzOptional[OnnxRegistry]onnx_registry)r[   r\   r`   ra   r^   zOptional[DiagnosticOptions]c                C  s(   || _ || _|| _|| _|p t | _d S N)r[   r\   r`   ra   r]   r^   )r6   r[   r\   r`   ra   r^   r)   r)   r*   r7   9  s
    
zExportOptions.__init__)r$   r%   r&   r'   r[   r(   r\   r`   ra   r   rY   r7   r)   r)   r)   r*   rZ     s   
rZ   c                   @  sr   e Zd ZU dZded< ded< ded< ded< d	ed
< ded< ded< ded< ded< ejddddddZdS )ResolvedExportOptionszConsolidates :class:`ExportOptions` with default values.
    All unspecified options from :class:`ExportOptions` are assigned a default value.
    This is an internal class and its API may be changed at any time without notice.
    rI   r[   r\   r]   r^   r!   r`   r+   ra   z%Dict[torch._ops.OpOverload, Callable]r   zFtorch.onnx._internal.fx.onnxfunction_dispatcher.OnnxFunctionDispatcheronnxfunction_dispatcherFXGraphExtractor	fx_tracerdiagnostics.DiagnosticContextdiagnostic_contextNz-Union[ExportOptions, 'ResolvedExportOptions']HOptional[Union[torch.nn.Module, Callable, torch_export.ExportedProgram]])optionsmodelc                 C  s  ddl m}m}m} t|tr|j| _|j| _|j| _|j	| _	t|t
jrxt|j|jsxd}t|}tt||j||j| _|j| _|j| _|j| _|j| _ntd}tjdddddd	}	|	|jd
| _|	|jt | _t|t
jr| | _n
| | _|	|j	d | _	|dtj| j| _|	|jt | _t| j| _ddl m}
 |	|jd
| _|
| j| j| _t |D ].}|!dsxt"| |sxt#d| dqxd S )Nr   )r   dynamo_graph_extractortorch_export_graph_extractorzP'model' of type 'ExportedProgram' is only supported with 'TorchExport' FX TracerTzOptional[T]zUnion[T, Callable[[], T]])valuefallbackr.   c                 S  s   | d k	r| S t |r| S |S rb   )callable)ro   rp   r)   r)   r*   resolve  s
    z/ResolvedExportOptions.__init__.<locals>.resolveFztorch.onnx.dynamo_export)rd   _zUnresolved option '')$torch.onnx._internal.fxr   rl   rm   
isinstancerc   r[   r\   r^   r`   torch_exportExportedProgramrf   ZTorchExportInvalidExportOptionsErrorONNXProgram_from_failurerh   ra   rd   r   r   r   rY   r]   ZDynamoExportZDiagnosticContexttorch__version__r+   Z(create_onnx_friendly_decomposition_tableZOnnxFunctionDispatcherdir
startswithhasattrAssertionError)r6   rj   rk   r   rl   rm   messageern   rr   rd   keyr)   r)   r*   r7   g  sj    
   
zResolvedExportOptions.__init__)N)r$   r%   r&   r'   r(   r   rY   r7   r)   r)   r)   r*   rc   J  s   
 rc   c               
   c  s~   ddl m}  ddlm} | jtj  |dddd}t	 }t
|d}| | |V  W 5 Q R X W 5 Q R X t|j|_dS )	aY  Enable fake mode for the duration of the context.

    Internally it instantiates a :class:`torch._subclasses.fake_tensor.FakeTensorMode` context manager
    that converts user input and model parameters into :class:`torch._subclasses.fake_tensor.FakeTensor`.

    A :class:`torch._subclasses.fake_tensor.FakeTensor`
    is a :class:`torch.Tensor` with the ability to run PyTorch code without having to
    actually do computation through tensors allocated on a ``meta`` device. Because
    there is no actual data being allocated on the device, this API allows for
    exporting large models without the actual memory footprint needed for executing it.

    It is highly recommended to enable fake mode when exporting models that
    are too large to fit into memory.

    Returns:
        A :class:`ONNXFakeContext` object that must be passed to :func:`dynamo_export`
        through the :attr:`ExportOptions.fake_context` argument.

    Example::

        # xdoctest: +REQUIRES(env:TORCH_DOCTEST_ONNX)
        >>> import torch
        >>> import torch.onnx
        >>> class MyModel(torch.nn.Module):  # Dummy model
        ...     def __init__(self) -> None:
        ...         super().__init__()
        ...         self.linear = torch.nn.Linear(2, 2)
        ...     def forward(self, x):
        ...         out = self.linear(x)
        ...         return out
        >>> with torch.onnx.enable_fake_mode() as fake_context:
        ...     my_nn_module = MyModel()
        ...     arg1 = torch.randn(2, 2, 2)  # positional input 1
        >>> export_options = torch.onnx.ExportOptions(fake_context=fake_context)
        >>> onnx_program = torch.onnx.dynamo_export(
        ...     my_nn_module,
        ...     arg1,
        ...     export_options=export_options
        ... )
        >>> # Saving model WITHOUT initializers
        >>> onnx_program.save("my_model_without_initializers.onnx")
        >>> # Saving model WITH initializers
        >>> onnx_program.save("my_model_with_initializers.onnx", model_state=MyModel().state_dict())

    .. warning::
        This API is experimental and is *NOT* backward-compatible.

    r   r   )ShapeEnvF)Zallow_scalar_outputsZallow_dynamic_output_shape_ops)Zallow_non_fake_inputsZ	shape_env)r"   N)torch._subclassesr   Z%torch.fx.experimental.symbolic_shapesr   ZFakeTensorModer|   Z_guardsZdetect_fake_moder   ZONNXTorchPatcherr!   tuplepathsr#   )r   r   r"   Zpatcher_contextr`   r)   r)   r*   enable_fake_mode  s     2
 
r   c                   @  s"   e Zd ZdZddddddZdS )	ONNXProgramSerializerzProtocol for serializing an ONNX graph into a specific format (e.g. Protobuf).
    Note that this is an advanced usage scenario.rz   io.BufferedIOBaser,   onnx_programdestinationr.   c                 C  s   dS )aa  Protocol method that must be implemented for serialization.

        Args:
            onnx_program: Represents the in-memory exported ONNX model
            destination: A binary IO stream or pre-allocated buffer into which
                the serialized model should be written.

        Example:

            A simple serializer that writes the exported :py:obj:`onnx.ModelProto` in Protobuf
            format to ``destination``:

            ::

                # xdoctest: +REQUIRES(env:TORCH_DOCTEST_ONNX)
                >>> import io
                >>> import torch
                >>> import torch.onnx
                >>> class MyModel(torch.nn.Module):  # Dummy model
                ...     def __init__(self) -> None:
                ...         super().__init__()
                ...         self.linear = torch.nn.Linear(2, 2)
                ...     def forward(self, x):
                ...         out = self.linear(x)
                ...         return out
                >>> class ProtobufONNXProgramSerializer:
                ...     def serialize(
                ...         self, onnx_program: torch.onnx.ONNXProgram, destination: io.BufferedIOBase
                ...     ) -> None:
                ...         destination.write(onnx_program.model_proto.SerializeToString())
                >>> model = MyModel()
                >>> arg1 = torch.randn(2, 2, 2)  # positional input 1
                >>> torch.onnx.dynamo_export(model, arg1).save(
                ...     destination="exported_model.onnx",
                ...     serializer=ProtobufONNXProgramSerializer(),
                ... )
        Nr)   )r6   r   r   r)   r)   r*   	serialize  s    (zONNXProgramSerializer.serializeN)r$   r%   r&   r'   r   r)   r)   r)   r*   r     s   r   c                   @  s(   e Zd ZdZejddddddZdS )	ProtobufONNXProgramSerializerz"Serializes ONNX graph as Protobuf.rz   r   r,   r   c                 C  s2   dd l }t|j|jstd||j  d S )Nr   z1onnx_program.ModelProto is not an onnx.ModelProto)onnxrv   model_proto
ModelProto
ValueErrorwriteSerializeToStringr6   r   r   r   r)   r)   r*   r   5  s    z'ProtobufONNXProgramSerializer.serializeN)r$   r%   r&   r'   r   rY   r   r)   r)   r)   r*   r   2  s   r   c                   @  s@   e Zd ZU dZded< ddddZejdd	d
dddZdS )"LargeProtobufONNXProgramSerializerzSerializes ONNX graph as Protobuf.

    Fallback to serializing as Protobuf with external data for models larger than 2GB.
    z
Final[str]_destination_pathrH   )destination_pathc                 C  s
   || _ d S rb   )r   )r6   r   r)   r)   r*   r7   H  s    z+LargeProtobufONNXProgramSerializer.__init__rz   r   r,   r   c                 C  sB   ddl }|j tk r(||j| j n|j|j| jddd dS )zQ`destination` is ignored. The model is saved to `self._destination_path` instead.r   NT)Zsave_as_external_dataZall_tensors_to_one_file)r   r   ZByteSize_PROTOBUF_SIZE_MAX_LIMITZ
save_modelr   r   r)   r)   r*   r   K  s    z,LargeProtobufONNXProgramSerializer.serializeN)	r$   r%   r&   r'   r(   r7   r   rY   r   r)   r)   r)   r*   r   @  s
   
r   c                   @  sX   e Zd ZU dZdZded< dZded< dZded< ej	dddd	dddd	d
dZ
dS )ONNXRuntimeOptionsaA  Options to influence the execution of the ONNX model through ONNX Runtime.

    Attributes:
        session_options: ONNX Runtime session options.
        execution_providers: ONNX Runtime execution providers to use during model execution.
        execution_provider_options: ONNX Runtime execution provider options.
    Nz0Optional[Sequence['onnxruntime.SessionOptions']]session_optionsz:Optional[Sequence[Union[str, Tuple[str, Dict[Any, Any]]]]]execution_providersz"Optional[Sequence[Dict[Any, Any]]]execution_provider_optionsr   r   r   c                C  s   || _ || _|| _d S rb   r   )r6   r   r   r   r)   r)   r*   r7   s  s    
zONNXRuntimeOptions.__init__)r$   r%   r&   r'   r   r(   r   r   r   rY   r7   r)   r)   r)   r*   r   _  s   

r   c                   @  sn  e Zd ZU dZded< ded< ded< ded	< d
ed< ded< ded< ded< ejddddddddddddddddZdddd dd!d d d"d#d$Ze	dd%d&d'Z
e	dd%d(d)Ze	dd%d*d+Ze	dd%d,d-Zejdd.dd/d0d1d2ZejdJd dd3d4d5d6Zejd7ddd8d9d:d;d<d=d>d?d@ZejdAd=dBdCdDZedEddFdGdHdIZdS )Krz   a  An in-memory representation of a PyTorch model that has been exported to ONNX.

    Args:
        model_proto: The exported ONNX model as an :py:obj:`onnx.ModelProto`.
        input_adapter: The input adapter used to convert PyTorch inputs into ONNX inputs.
        output_adapter: The output adapter used to convert PyTorch outputs into ONNX outputs.
        diagnostic_context: Context object for the SARIF diagnostic system responsible for logging errors and metadata.
        fake_context: The fake context used for symbolic tracing.
        export_exception: The exception that occurred during export, if any.
        model_signature: The model signature for the exported ONNX graph.
    zFinal[onnx.ModelProto]_model_protozFinal[io_adapter.InputAdapter]_input_adapterzFinal[io_adapter.OutputAdapter]_output_adapterz$Final[diagnostics.DiagnosticContext]_diagnostic_contextz Final[Optional[ONNXFakeContext]]_fake_contextzFinal[Optional[Exception]]_export_exceptionz2Final[Optional[torch.export.ExportGraphSignature]]_model_signaturezOFinal[Optional[Union[torch.nn.Module, Callable, torch_export.ExportedProgram]]]_model_torchN)r`   export_exceptionmodel_signaturemodel_torchzonnx.ModelProtozio_adapter.InputAdapterzio_adapter.OutputAdapterrg   r_   zOptional[Exception]z+Optional[torch.export.ExportGraphSignature]ri   )r   input_adapteroutput_adapterrh   r`   r   r   r   c          	      C  s4   || _ || _|| _|| _|| _|| _|| _|| _d S rb   )r   r   r   r   r   r   r   r   )	r6   r   r   r   rh   r`   r   r   r   r)   r)   r*   r7     s    zONNXProgram.__init__)model_with_state_dictrj   r   zOptional[ONNXRuntimeOptions])argsr   rj   kwargsr.   c             
   O  s  t  }|p| j}| jr|t }td t	j
|d}t|tjjrX| }nt|tjrl|j}nd}| j||d n
| j }ddl}	| j|d|i|}
|pt }|jp|	 }|	j||d}dd	 t| |
D }|d|W  5 Q R  S Q R X dS )
a  Runs the ONNX model using ONNX Runtime

        Args:
            args: The positional inputs to the model.
            kwargs: The keyword inputs to the model.
            model_with_state_dict: The PyTorch model to fetch state from.
                Required when :func:`enable_fake_mode` is used to extract real initializers as needed by the ONNX graph.
            options: The options to use for running the model with ONNX Runtime.

        Returns:
            The model output as computed by ONNX Runtime
        zCannot run model directly from `ONNXProgram` because the model was exported using `enable_fake_mode`. The model will be serialized to disk using a temporary folder ({tmpdir_path}) to populate the model with initializers before being execution.z
model.onnxN)model_stater   r   )	providersc                 S  s    i | ]\}}|j |jd dqS )T)force)namenumpy)rT   kvr)   r)   r*   
<dictcomp>  s    z(ONNXProgram.__call__.<locals>.<dictcomp>)
contextlib	ExitStackr   r`   enter_contexttempfileTemporaryDirectoryr3   r4   ospathjoinrv   r|   nnModuleZ
state_dictrw   rx   saver   r   onnxruntimeadapt_torch_inputs_to_onnxr   r   Zget_available_providersZInferenceSessionzip
get_inputsrun)r6   r   rj   r   r   stackZtmpdir_path
onnx_modelr   r   Z
onnx_inputr   Zort_sessionZonnxruntime_inputr)   r)   r*   __call__  sD    




zONNXProgram.__call__r-   c                 C  s   | j dk	r| j | jS )z8The exported ONNX model as an :py:obj:`onnx.ModelProto`.N)r   r   r9   r)   r)   r*   r     s    
zONNXProgram.model_protoc                 C  s   | j S )a-  The model signature for the exported ONNX graph.

        This information is relevant because ONNX specification often differs from PyTorch's, resulting
        in a ONNX graph with input and output schema different from the actual PyTorch model implementation.
        By using the model signature, the users can understand the inputs and outputs differences
        and properly execute the model in ONNX Runtime.

        NOTE: Model signature is only available when the ONNX graph was exported from a
        :class:`torch.export.ExportedProgram` object.

        NOTE: Any transformation done to the model that changes the model signature must be accompanied
        by updates to this model signature as well through :class:`InputAdaptStep` and/or :class:`OutputAdaptStep`.

        Example:

            The following model produces different sets of inputs and outputs.
            The first 4 inputs are model parameters (namely conv1.weight, conv2.weight, fc1.weight, fc2.weight),
            and the next 2 inputs are registered buffers (namely my_buffer2, my_buffer1) and finally
            the last 2 inputs are user inputs (namely x and b).
            The first output is a buffer mutation (namely my_buffer2) and the last output is the actual model output.

            >>> import pprint
            >>> class CustomModule(torch.nn.Module):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self.my_parameter = torch.nn.Parameter(torch.tensor(2.0))
            ...         self.register_buffer("my_buffer1", torch.tensor(3.0))
            ...         self.register_buffer("my_buffer2", torch.tensor(4.0))
            ...         self.conv1 = torch.nn.Conv2d(1, 32, 3, 1, bias=False)
            ...         self.conv2 = torch.nn.Conv2d(32, 64, 3, 1, bias=False)
            ...         self.fc1 = torch.nn.Linear(9216, 128, bias=False)
            ...         self.fc2 = torch.nn.Linear(128, 10, bias=False)
            ...     def forward(self, x, b):
            ...         tensor_x = self.conv1(x)
            ...         tensor_x = torch.nn.functional.sigmoid(tensor_x)
            ...         tensor_x = self.conv2(tensor_x)
            ...         tensor_x = torch.nn.functional.sigmoid(tensor_x)
            ...         tensor_x = torch.nn.functional.max_pool2d(tensor_x, 2)
            ...         tensor_x = torch.flatten(tensor_x, 1)
            ...         tensor_x = self.fc1(tensor_x)
            ...         tensor_x = torch.nn.functional.sigmoid(tensor_x)
            ...         tensor_x = self.fc2(tensor_x)
            ...         output = torch.nn.functional.log_softmax(tensor_x, dim=1)
            ...         (
            ...         self.my_buffer2.add_(1.0) + self.my_buffer1
            ...         )  # Mutate buffer through in-place addition
            ...         return output
            >>> inputs = (torch.rand((64, 1, 28, 28), dtype=torch.float32), torch.randn(3))
            >>> exported_program = torch.export.export(CustomModule(), args=inputs).run_decompositions({})
            >>> onnx_program = torch.onnx.dynamo_export(exported_program, *inputs)
            >>> pprint.pprint(onnx_program.model_signature)
            ExportGraphSignature(input_specs=[InputSpec(kind=<InputKind.PARAMETER: 2>,
                                                  arg=TensorArgument(name='p_conv1_weight'),
                                                  target='conv1.weight',
                                                  persistent=None),
                                        InputSpec(kind=<InputKind.PARAMETER: 2>,
                                                  arg=TensorArgument(name='p_conv2_weight'),
                                                  target='conv2.weight',
                                                  persistent=None),
                                        InputSpec(kind=<InputKind.PARAMETER: 2>,
                                                  arg=TensorArgument(name='p_fc1_weight'),
                                                  target='fc1.weight',
                                                  persistent=None),
                                        InputSpec(kind=<InputKind.PARAMETER: 2>,
                                                  arg=TensorArgument(name='p_fc2_weight'),
                                                  target='fc2.weight',
                                                  persistent=None),
                                        InputSpec(kind=<InputKind.BUFFER: 3>,
                                                  arg=TensorArgument(name='b_my_buffer2'),
                                                  target='my_buffer2',
                                                  persistent=True),
                                        InputSpec(kind=<InputKind.BUFFER: 3>,
                                                  arg=TensorArgument(name='b_my_buffer1'),
                                                  target='my_buffer1',
                                                  persistent=True),
                                        InputSpec(kind=<InputKind.USER_INPUT: 1>,
                                                  arg=TensorArgument(name='x'),
                                                  target=None,
                                                  persistent=None),
                                        InputSpec(kind=<InputKind.USER_INPUT: 1>,
                                                  arg=TensorArgument(name='b'),
                                                  target=None,
                                                  persistent=None)],
                           output_specs=[OutputSpec(kind=<OutputKind.BUFFER_MUTATION: 3>,
                                                    arg=TensorArgument(name='add'),
                                                    target='my_buffer2'),
                                         OutputSpec(kind=<OutputKind.USER_OUTPUT: 1>,
                                                    arg=TensorArgument(name='_log_softmax'),
                                                    target=None)])
        )r   r9   r)   r)   r*   r     s    ]zONNXProgram.model_signaturec                 C  s   | j S )z2The diagnostic context associated with the export.)r   r9   r)   r)   r*   rh   ^  s    zONNXProgram.diagnostic_contextc                 C  s   | j S )z,The fake context associated with the export.)r   r9   r)   r)   r*   r`   d  s    zONNXProgram.fake_context)r   z<Sequence[Union[torch.Tensor, int, float, bool, torch.dtype]])r   r.   c                O  s0   |p| j }|dk	std| jj|d|i|S )a	  Converts the PyTorch model inputs to exported ONNX model inputs format.

        Due to design differences, input/output format between PyTorch model and exported
        ONNX model are often not the same. E.g., None is allowed for PyTorch model, but are
        not supported by ONNX. Nested constructs of tensors are allowed for PyTorch model,
        but only flattened tensors are supported by ONNX, etc.

        The actual adapting steps are associated with each individual export. It
        depends on the PyTorch model, the particular set of model_args and model_kwargs
        used for the export, and export options.

        This method replays the adapting steps recorded during export.

        Args:
            model_args: The PyTorch model inputs.
            model_with_state_dict: The PyTorch model to get extra state from.
                If not specified, the model used during export is used.
                Required when :func:`enable_fake_mode` is used to extract real initializers as needed by the ONNX graph.
            model_kwargs: The PyTorch model keyword inputs.

        Returns:
            A sequence of tensors converted from PyTorch model inputs.

        Example::

            # xdoctest: +REQUIRES(env:TORCH_DOCTEST_ONNX)
            >>> import torch
            >>> import torch.onnx
            >>> from typing import Dict, Tuple
            >>> def func_nested_input(
            ...     x_dict: Dict[str, torch.Tensor],
            ...     y_tuple: Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
            ... ):
            ...     if "a" in x_dict:
            ...         x = x_dict["a"]
            ...     elif "b" in x_dict:
            ...         x = x_dict["b"]
            ...     else:
            ...         x = torch.randn(3)
            ...
            ...     y1, (y2, y3) = y_tuple
            ...
            ...     return x + y1 + y2 + y3
            >>> x_dict = {"a": torch.tensor(1.)}
            >>> y_tuple = (torch.tensor(2.), (torch.tensor(3.), torch.tensor(4.)))
            >>> onnx_program = torch.onnx.dynamo_export(func_nested_input, x_dict, y_tuple)
            >>> print(x_dict, y_tuple)
            {'a': tensor(1.)} (tensor(2.), (tensor(3.), tensor(4.)))
            >>> print(onnx_program.adapt_torch_inputs_to_onnx(x_dict, y_tuple, model_with_state_dict=func_nested_input))
            (tensor(1.), tensor(2.), tensor(3.), tensor(4.))

        .. warning::
            This API is experimental and is *NOT* backward-compatible.

        N(model_with_state_dict must be specified.rk   )r   r   r   apply)r6   r   
model_argsmodel_kwargsr)   r)   r*   r   j  s    A
z&ONNXProgram.adapt_torch_inputs_to_onnxz/Sequence[Union[torch.Tensor, int, float, bool]])model_outputsr   r.   c                 C  s*   |p| j }|dk	std| jj||dS )a  Converts the PyTorch model outputs to exported ONNX model outputs format.

        Due to design differences, input/output format between PyTorch model and exported
        ONNX model are often not the same. E.g., None is allowed for PyTorch model, but are
        not supported by ONNX. Nested constructs of tensors are allowed for PyTorch model,
        but only flattened tensors are supported by ONNX, etc.

        The actual adapting steps are associated with each individual export. It
        depends on the PyTorch model, the particular set of model_args and model_kwargs
        used for the export, and export options.

        This method replays the adapting steps recorded during export.

        Args:
            model_outputs: The PyTorch model outputs.
            model_with_state_dict: The PyTorch model to get extra state from.
                If not specified, the model used during export is used.
                Required when :func:`enable_fake_mode` is used to extract real initializers as needed by the ONNX graph.

        Returns:
            PyTorch model outputs in exported ONNX model outputs format.

        Example::

            # xdoctest: +REQUIRES(env:TORCH_DOCTEST_ONNX)
            >>> import torch
            >>> import torch.onnx
            >>> def func_returning_tuples(x, y, z):
            ...     x = x + y
            ...     y = y + z
            ...     z = x + y
            ...     return (x, (y, z))
            >>> x = torch.tensor(1.)
            >>> y = torch.tensor(2.)
            >>> z = torch.tensor(3.)
            >>> onnx_program = torch.onnx.dynamo_export(func_returning_tuples, x, y, z)
            >>> pt_output = func_returning_tuples(x, y, z)
            >>> print(pt_output)
            (tensor(3.), (tensor(5.), tensor(8.)))
            >>> print(onnx_program.adapt_torch_outputs_to_onnx(pt_output, model_with_state_dict=func_returning_tuples))
            [tensor(3.), tensor(5.), tensor(8.)]

        .. warning::
            This API is experimental and is *NOT* backward-compatible.

        Nr   rk   )r   r   r   r   )r6   r   r   r)   r)   r*   adapt_torch_outputs_to_onnx  s    7
z'ONNXProgram.adapt_torch_outputs_to_onnxT)include_initializersr   
serializerzUnion[str, io.BufferedIOBase]rI   z$Optional[Union[Dict[str, Any], str]]zOptional[ONNXProgramSerializer]r,   )r   r   r   r   r.   c             
   C  s  |dks|dkst d|dkr:t|tr4t|}nt }g }|r|dk	rlt|ttfs`t d|| q| jr| jjr| jjD ]$}||krqt	j
|r|| qn(t| jjj}t|D ]}| jjjd= q|r&t|tstdt	j
|\}	}
|	pt	 }	|
}t|	|dt|| j npt|trVt|d}|| | W 5 Q R X n@z|| | W n. tk
r } ztd	|W 5 d}~X Y nX dS )
aP  Saves the in-memory ONNX model to ``destination`` using specified ``serializer``.

        Args:
            destination: The destination to save the ONNX model. It can be either a string or a file-like object.
                When used with ``model_state``, it must be a string with a full path to the destination.
                If `destination` is a string, besides saving the ONNX model into a file, model weights are also stored
                in separate files in the same directory as the ONNX model. E.g. for `destination="/path/model.onnx"`,
                the initializers are saved in "/path/" folder along with "onnx.model".
            include_initializers: Whether to include initializers in the ONNX graph as external data.
                Cannot be combined with `model_state_dict`.
            model_state: The state_dict of the PyTorch model containing all weights on it.
                It can be either a string with the path to a checkpoint or a dictionary with the actual model state.
                The supported file formats are the same as those supported by `torch.load` and `safetensors.safe_open`.
                Required when :func:`enable_fake_mode` is used but real initializers are needed on the ONNX graph.
            serializer: The serializer to use. If not specified, the model will be serialized as Protobuf.
        TNzCCannot specify both `include_initializers=False` and `model_state`.zMmodel_state must be a path to the model's state_dict or the actual state_dictr   zK`destination` must be a string with a path when `model_state` is specified. wbz'destination' should be provided as a path-like string when saving a model larger than 2GB. External tensor data will be saved alongside the model on disk.)r   rv   rH   r   r   dictrG   r   r#   r   r   existslenr   graphinitializerrangeRuntimeErrorsplitgetcwdfx_serializationZsave_model_with_external_datar   openr   r   )r6   r   r   r   r   Z_model_state_filesr   Zinitializer_countrs   r   Zdestination_filenameZonnx_model_locationfexcr)   r)   r*   r     sn    

 
zONNXProgram.saverH   )r   r.   c                 C  s6   | ds&d| }t| t|| j| dS )aL  Saves the export diagnostics as a SARIF log to the specified destination path.

        Args:
            destination: The destination to save the diagnostics SARIF log.
                It must have a `.sarif` extension.

        Raises:
            ValueError: If the destination path does not end with `.sarif` extension.
        z.sarifz0'destination' must have a .sarif extension, got N)endswithlogfatalr   rh   dump)r6   r   r   r)   r)   r*   save_diagnosticsI  s
    


zONNXProgram.save_diagnostics	Exceptionr   )r   rh   r.   c                 C  s&   ddl }t| t t ||dS )aZ  
        Creates an instance of :class:`ONNXProgram` when the export process encounters a failure.

        In case of a failed export, this method is used to encapsulate the exception
        and associated diagnostic context within an :class:`ONNXProgram` instance for
        easier handling and debugging.

        Args:
            export_exception: The exception raised during the export process.
            diagnostic_context: The context associated with diagnostics during export.

        Returns:
            An instance of :class:`ONNXProgram` representing the failed ONNX program.
        r   N)r   )r   rz   r   r   InputAdapterOutputAdapter)clsr   rh   r   r)   r)   r*   r{   [  s    zONNXProgram._from_failure)N)r$   r%   r&   r'   r(   r   rY   r7   r   rX   r   r   rh   r`   r   r   r   r   classmethodr{   r)   r)   r)   r*   rz     sR   
"E^H <Xrz   c                      s\   e Zd ZdZdd fddZejdddd	d
dddZejddd
ddddZ  Z	S )re   zAbstract interface for FX graph extractor engines.
    This class isolates FX extraction logic from the rest of the export logic.
    That allows a single ONNX exporter that can leverage different FX graphs.r,   r-   c                   s"   t    t | _t | _d S rb   )superr7   r   r   r   r   r   r9   	__class__r)   r*   r7     s    

zFXGraphExtractor.__init__rc    Union[torch.nn.Module, Callable]Sequence[Any]Mapping[str, Any]torch.fx.GraphModule)rj   rk   r   r   r.   c                 C  s   dS )aH  Analyzes user ``model`` and generates a FX graph.
        Args:
            options: The export options.
            model: The user model.
            model_args: The model's positional input arguments.
            model_kwargs: The model's keyword input arguments.
        Returns:
            The generated FX Graph.
        Nr)   )r6   rj   rk   r   r   r)   r)   r*   generate_fx  s    zFXGraphExtractor.generate_fxrj   original_model	fx_modulefx_module_argsc                 C  s   dS )ab  Applies pre-export passes to the FX graph.

        Pre-export passes are FX-to-FX graph transformations that make the graph
        more palatable for the FX-to-ONNX conversion.
        For example, it can be used to flatten model input/output, add explicit
        casts to the graph, replace/decompose operators, functionalize the graph, etc.
        Nr)   )r6   rj   r   r   r   r)   r)   r*   pre_export_passes  s    z"FXGraphExtractor.pre_export_passes)
r$   r%   r&   r'   r7   abcabstractmethodr   r   __classcell__r)   r)   r   r*   re   }  s   re   c                   @  s<   e Zd ZejdddddddZdd	d
dZdd ZdS )Exporterrc   >Union[torch.nn.Module, Callable, torch_export.ExportedProgram]r   r   rj   rk   r   r   c                 C  sN   || _ | j d k	st|| _|| _|| _ddlm} t| j j|j	sJ| 
  d S )Nr   )fx_symbolic_graph_extractor)rj   r   rk   r   r   ru   r  rv   rf   ZFXSymbolicTracer_assert_fake_tensor_mode)r6   rj   rk   r   r   r  r)   r)   r*   r7     s     zExporter.__init__rz   r-   c                 C  s  ddl m} ddlm} | jj || j tjj	
t|n | jj| j| j| j| j}ddlm} |j| jjd}|j|| jj| jjd}| jjd k	ri }|j D ]\}}	t|	tjjs|	||< q||_|| jjj}
zddl m!} |"|
}
W nR t#k
r&   t$%d Y n4 t&k
rX } zt$%d	|  W 5 d }~X Y nX tj'j(|
| jjj)| jjj*| jj| jjt+| jd
d | jdW  5 Q R  W  5 Q R  W  5 Q R  S Q R X W 5 Q R X W 5 Q R X d S )Nr   )DEFAULT_EXPORT_DYNAMO_CONFIG)decomposition_skip)fx_onnx_interpreter)rh   )Zfx_graph_modulerd   r\   )	optimizerzONNXScript optimizer is not available. Skipping optimization. Please `pip install onnxscript -U` to enable post-export optimization.zONNXScript optimizer failed. Skipping optimization. 

PLEASE REPORT A BUG AT https://github.com/microsoft/onnxscript/issues 

Detail:
Zgraph_signature)r`   r   r   ),Ztorch.export._tracer  ru   r  rj   rh   Zenable_decomposition_skipsr|   Z_dynamoconfigpatchdataclassesasdictrf   r   rk   r   r   r  ZFxOnnxInterpreterr   rd   r\   r`   Zinitializersr>   rv   _subclasses
FakeTensorZto_model_protora   r:   
onnxscriptr  optimizeImportErrorr3   r4   r   r   rz   r   r   getattr)r6   r  r  Zgraph_moduler  Zfx_interpreterZonnxscript_graphZinitializers_with_real_tensorsZinitializer_namer   r   r  r   r)   r)   r*   export  sx       

  zExporter.exportc                 C  s   t dd | j| jf}d}t| jtjjrLt dd | j	 | j
 f}|sT|rd| jjsdtdt dd | j| jf}d}t| jtjjrt dd | j	 | j
 f}|s|r| jjrtdd	S )
zAAsserts that the model and its input do not contain fake tensors.c                 S  s   t | tjjS rb   rv   r|   r  r  xr)   r)   r*   <lambda>      z3Exporter._assert_fake_tensor_mode.<locals>.<lambda>Fc                 S  s   t | tjjS rb   r  r  r)   r)   r*   r    r  zJCannot export a model with fake inputs/weights without enabling fake mode.c                 S  s   t | tjot | tjj S rb   rv   r|   ZTensorr  r  r  r)   r)   r*   r  )  s   c                 S  s   t | tjot | tjj S rb   r  r  r)   r)   r*   r  0  s   zICannot export a model with non fake inputs/weights and enabled fake mode.N)pytreeZtree_anyr   r   rv   rk   r|   r   r   
parametersbuffersrj   r`   r   )r6   Zhas_any_fake_tensorZhas_any_fake_param_or_bufferZhas_any_non_fake_tensorsZ has_any_non_fake_param_or_bufferr)   r)   r*   r    sL    

z!Exporter._assert_fake_tensor_modeN)r$   r%   r&   r   rY   r7   r  r  r)   r)   r)   r*   r     s   Mr   c                      s(   e Zd ZdZddd fddZ  ZS )UnsatisfiedDependencyErrorz<Raised when an ONNX exporter dependency cannot be satisfied.rH   package_namer   c                   s   t  | || _d S rb   )r   r7   r  )r6   r  r   r   r)   r*   r7   ?  s    z#UnsatisfiedDependencyError.__init__)r$   r%   r&   r'   r7   r   r)   r)   r   r*   r  <  s   r  c                      s2   e Zd ZU dZded< ddd fddZ  ZS )	OnnxExporterErrora  Raised when an ONNX exporter error occurs.

    This exception is thrown when there's an error during the ONNX export process.
    It encapsulates the :class:`ONNXProgram` object generated until the failure, allowing
    access to the partial export results and associated metadata.
    zFinal[ONNXProgram]r   rz   rH   )r   r   c                   s   t  | || _dS )z
        Initializes the OnnxExporterError with the given ONNX program and message.

        Args:
            onnx_program (ONNXProgram): The partial results of the ONNX export.
            message (str): The error message to be displayed.
        N)r   r7   r   )r6   r   r   r   r)   r*   r7   N  s    zOnnxExporterError.__init__)r$   r%   r&   r'   r(   r7   r   r)   r)   r   r*   r  D  s   
r  c                   @  s   e Zd ZdZdS )ry   zKRaised when user specified an invalid value for the :class:`ExportOptions`.N)r$   r%   r&   r'   r)   r)   r)   r*   ry   Z  s   ry   )export_optionsc              
     s   | j j ddddd}dd fdd}zd	d l}W n. tk
rd } z|d
||W 5 d }~X Y nX |j  k r||d
zd	d l}W n. tk
r } z|d||W 5 d }~X Y nX t|jj	d f |j
js|dd S )NrH   zlogging._ExcInfoType)r  exc_infoc                 S  s*   d|  d|  d}t j||d t| |S )NzPlease install the `z'` package (e.g. `python -m pip install z`).)r   r   r   r  )r  r   r   r)   r)   r*   missing_packaged  s    z-_assert_dependencies.<locals>.missing_package)r  c                   s,   d|  d  d|  d}t | t| |S )NzThe installed `z4` does not support the specified ONNX opset version z. Install a newer `z,` package or specify an older opset version.r!  r  r:   r)   r*   missing_opsetl  s    
z+_assert_dependencies.<locals>.missing_opsetr   r   r  r   )ra   r:   r   r  ZdefsZonnx_opset_versionr  rv   Z
onnx_opsetZ
all_opsetsvaluesZOpset)r  r"  r$  r   r   r  r)   r#  r*   _assert_dependencies`  s$    	r&  r   zOptional[ExportOptions])rk   r  r.   c            
   O  s   |dk	r$t |tr|n
t|| d}ntt | d}t| zt|| ||d W S  tk
r } z:t}|j	| d| dt
 }tt||j||W 5 d}~X Y nX dS )aQ  Export a torch.nn.Module to an ONNX graph.

    Args:
        model: The PyTorch model to be exported to ONNX.
        model_args: Positional inputs to ``model``.
        model_kwargs: Keyword inputs to ``model``.
        export_options: Options to influence the export to ONNX.

    Returns:
        An in-memory representation of the exported ONNX model.

    **Example 1 - Simplest export**
    ::

        class MyModel(torch.nn.Module):
            def __init__(self) -> None:
                super().__init__()
                self.linear = torch.nn.Linear(2, 2)
            def forward(self, x, bias=None):
                out = self.linear(x)
                out = out + bias
                return out
        model = MyModel()
        kwargs = {"bias": 3.}
        args = (torch.randn(2, 2, 2),)
        onnx_program = torch.onnx.dynamo_export(
            model,
            *args,
            **kwargs).save("my_simple_model.onnx")

    **Example 2 - Exporting with dynamic shapes**
    ::

        # The previous model can be exported with dynamic shapes
        export_options = torch.onnx.ExportOptions(dynamic_shapes=True)
        onnx_program = torch.onnx.dynamo_export(
            model,
            *args,
            **kwargs,
            export_options=export_options)
        onnx_program.save("my_dynamic_model.onnx")


    By printing input dynamic dimensions we can see the input shape is no longer (2,2,2)
    ::

        >>> print(onnx_program.model_proto.graph.input[0])
        name: "arg0"
        type {
          tensor_type {
            elem_type: 1
            shape {
              dim {
                dim_param: "arg0_dim_0"
              }
              dim {
                dim_param: "arg0_dim_1"
              }
              dim {
                dim_param: "arg0_dim_2"
              }
            }
          }
        }
    Nr   r   z@Failed to export the model to ONNX. Generating SARIF report at 'z'. SARIF is a standard format for the output of static analysis tools. SARIF logs can be loaded in VS Code SARIF viewer extension, or SARIF web viewer (https://microsoft.github.io/sarif-web-component/). Please report a bug on PyTorch Github: )rv   rc   rZ   r&  r   r  r   %_DEFAULT_FAILED_EXPORT_SARIF_LOG_PATHrh   r   _PYTORCH_GITHUB_ISSUES_URLr  rz   r{   )rk   r  r   r   Zresolved_export_optionsr   Zsarif_report_pathr   r)   r)   r*   dynamo_export  s2    J
r)  r   r   r   r   c                 C  s$  ddl m}m} | j}|j||| j| j| jd k	dj| }|j	||| j| jd k	dj| }|
||j| }||| }|||| jtjj t|tjjr|||| }||| }| jjt  | jjt  | jjt  | jjt   | jjt!  |S )Nr   )analysispasses)Zenable_dynamic_axesZallow_fake_constant)"ru   r*  r+  rh   Z	Decomposer   r[   r`   r   ZFunctionalizeZRemoveInputMutationZInsertTypePromotionZUnsupportedFxNodesAnalysisrd   Zanalyzer   ZlevelsERRORrv   r|   r   r   ZRestoreParameterAndBufferNamesZ
Modularizerf   r   Zappend_stepr   ZRemoveNoneInputStepZRemoveNonTensorInputStepZ+ConvertComplexToRealRepresentationInputStepr   ZFlattenOutputStepZ,ConvertComplexToRealRepresentationOutputStep)rj   r   r   r   r*  r+  rh   moduler)   r)   r*   common_pre_export_passes  sZ    
	    r.  r]   )\
__future__r   r   r   r	  iologgingr   r   r3   collectionsr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   typing_extensionsr   r|   Z
torch._opsZtorch.exportr  rw   Ztorch.utils._pytreeutilsZ_pytreer  r   r   Ztorch.onnx._internalr   r   Z torch.onnx._internal.diagnosticsr   ru   r   r   r   r   r   r   r   r  r1   r;   r   r  r    r(   r(  r'  r   	getLoggerr$   r   r]   	dataclassr!   r+   rZ   rc   contextmanagerr   r   r   r   r   rz   ABCre   r   r   r  r  ry   rY   r&  r)  r.  __all__r)   r)   r)   r*   <module>   s    D

 )3n
I/#   ~0 )kN