a
    hT                      @  s>  d dl mZ g dZd dlmZmZmZ d dlmZ d dl	Z	d dl
mZ d dlmZmZm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 ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'mZm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m!Z! er6d dl9Z9d dl:m;Z;m<Z<m=Z= de_>de_>de _>de_>de_>de_>de_>de_>dZ?ej@ZAd9dddddddddddddddddddejjBejjCddddddddddddddd dddd!d"dddddd#dd$d%dd&d'dd(d)d*d+ZDed,G d-d. d.ZEed,dd/d0d1d2d3d4d5ZFdd6d7d8ZGdS ):    )annotations)"errorsopssymbolic_helperutilssymbolic_caffe2symbolic_opset7symbolic_opset8symbolic_opset9symbolic_opset10symbolic_opset11symbolic_opset12symbolic_opset13symbolic_opset14symbolic_opset15symbolic_opset16symbolic_opset17symbolic_opset18symbolic_opset19symbolic_opset20OperatorExportTypesTrainingModeTensorProtoDataTypeJitScalarTypeexportis_in_onnx_exportselect_model_mode_for_exportregister_custom_op_symbolicunregister_custom_op_symbolicOnnxExporterErrorExportOptionsONNXProgramdynamo_exportenable_fake_modeis_onnxrt_backend_supported)AnyCallableTYPE_CHECKING)
deprecatedN)_onnx)r   r   r      )r#   )r!   )r$   
OrtBackendOrtBackendOptionsOrtExecutionProvider)r   )r   )_run_symbolic_function_run_symbolic_methodr   r   r   )r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   )
CollectionMappingSequencez
torch.onnxZpytorch TF.)kwargsexport_paramsverboseinput_namesoutput_namesopset_versiondynamic_axeskeep_initializers_as_inputsdynamoexternal_datadynamic_shapescustom_translation_tablereportoptimizeverifyprofiledump_exported_programartifacts_dirfallbacktrainingoperator_export_typedo_constant_foldingcustom_opsetsexport_modules_as_functionsautograd_inliningzbtorch.nn.Module | torch.export.ExportedProgram | torch.jit.ScriptModule | torch.jit.ScriptFunctionztuple[Any, ...]zstr | os.PathLike | Nonezdict[str, Any] | Noneboolbool | NonezSequence[str] | Nonez
int | NonezDMapping[str, Mapping[int, str]] | Mapping[str, Sequence[int]] | Nonez3dict[str, Any] | tuple[Any, ...] | list[Any] | Nonez4dict[Callable, Callable | Sequence[Callable]] | Nonezstr | os.PathLikez_C_onnx.TrainingModez_C_onnx.OperatorExportTypeszMapping[str, int] | Nonez(bool | Collection[type[torch.nn.Module]]zONNXProgram | None)modelargsfr5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   returnc                 C  s   |du st | tjjr|ddlm} t |tjr4|f}||||||d}|j| ||||||||||	|
||||||||||dS ddl}ddl	m} |j
dtd	d
 |rtd|| |||||du ||||	|
||||||d dS dS )a<)  Exports a model into ONNX format.

    Setting ``dynamo=True`` enables the new ONNX export logic
    which is based on :class:`torch.export.ExportedProgram` and a more modern
    set of translation logic. This is the recommended way to export models
    to ONNX.

    When ``dynamo=True``:

    The exporter tries the following strategies to get an ExportedProgram for conversion to ONNX.

    #. If the model is already an ExportedProgram, it will be used as-is.
    #. Use :func:`torch.export.export` and set ``strict=False``.
    #. Use :func:`torch.export.export` and set ``strict=True``.
    #. Use ``draft_export`` which removes some soundness guarantees in data-dependent
       operations to allow export to proceed. You will get a warning if the exporter
       encounters any unsound data-dependent operation.
    #. Use :func:`torch.jit.trace` to trace the model then convert to ExportedProgram.
       This is the most unsound strategy but may be useful for converting TorchScript
       models to ONNX.

    Args:
        model: The model to be exported.
        args: Example positional inputs. Any non-Tensor arguments will be hard-coded into the
            exported model; any Tensor arguments will become inputs of the exported model,
            in the order they occur in the tuple.
        f: Path to the output ONNX model file. E.g. "model.onnx".
        kwargs: Optional example keyword inputs.
        export_params: If false, parameters (weights) will not be exported.
        verbose: Whether to enable verbose logging.
        input_names: names to assign to the input nodes of the graph, in order.
        output_names: names to assign to the output nodes of the graph, in order.
        opset_version: The version of the
            `default (ai.onnx) opset <https://github.com/onnx/onnx/blob/master/docs/Operators.md>`_
            to target. Must be >= 7.
        dynamic_axes:

            By default the exported model will have the shapes of all input and output tensors
            set to exactly match those given in ``args``. To specify axes of tensors as
            dynamic (i.e. known only at run-time), set ``dynamic_axes`` to a dict with schema:

            * KEY (str): an input or output name. Each name must also be provided in ``input_names`` or
                ``output_names``.
            * VALUE (dict or list): If a dict, keys are axis indices and values are axis names. If a
                list, each element is an axis index.

            For example::

                class SumModule(torch.nn.Module):
                    def forward(self, x):
                        return torch.sum(x, dim=1)


                torch.onnx.export(
                    SumModule(),
                    (torch.ones(2, 2),),
                    "onnx.pb",
                    input_names=["x"],
                    output_names=["sum"],
                )

            Produces::

                input {
                  name: "x"
                  ...
                      shape {
                        dim {
                          dim_value: 2  # axis 0
                        }
                        dim {
                          dim_value: 2  # axis 1
                ...
                output {
                  name: "sum"
                  ...
                      shape {
                        dim {
                          dim_value: 2  # axis 0
                ...

            While::

                torch.onnx.export(
                    SumModule(),
                    (torch.ones(2, 2),),
                    "onnx.pb",
                    input_names=["x"],
                    output_names=["sum"],
                    dynamic_axes={
                        # dict value: manually named axes
                        "x": {0: "my_custom_axis_name"},
                        # list value: automatic names
                        "sum": [0],
                    },
                )

            Produces::

                input {
                  name: "x"
                  ...
                      shape {
                        dim {
                          dim_param: "my_custom_axis_name"  # axis 0
                        }
                        dim {
                          dim_value: 2  # axis 1
                ...
                output {
                  name: "sum"
                  ...
                      shape {
                        dim {
                          dim_param: "sum_dynamic_axes_1"  # axis 0
                ...

        keep_initializers_as_inputs: If True, all the
            initializers (typically corresponding to model weights) in the
            exported graph will also be added as inputs to the graph. If False,
            then initializers are not added as inputs to the graph, and only
            the user inputs are added as inputs.

            Set this to True if you intend to supply model weights at runtime.
            Set it to False if the weights are static to allow for better optimizations
            (e.g. constant folding) by backends/runtimes.

        dynamo: Whether to export the model with ``torch.export`` ExportedProgram instead of TorchScript.
        external_data: Whether to save the model weights as an external data file.
            This is required for models with large weights that exceed the ONNX file size limit (2GB).
            When False, the weights are saved in the ONNX file with the model architecture.
        dynamic_shapes: A dictionary or a tuple of dynamic shapes for the model inputs. Refer to
            :func:`torch.export.export` for more details. This is only used (and preferred) when dynamo is True.
            Note that dynamic_shapes is designed to be used when the model is exported with dynamo=True, while
            dynamic_axes is used when dynamo=False.
        custom_translation_table: A dictionary of custom decompositions for operators in the model.
            The dictionary should have the callable target in the fx Node as the key (e.g. ``torch.ops.aten.stft.default``),
            and the value should be a function that builds that graph using ONNX Script. This option
            is only valid when dynamo is True.
        report: Whether to generate a markdown report for the export process. This option
            is only valid when dynamo is True.
        optimize: Whether to optimize the exported model. This option
            is only valid when dynamo is True. Default is True.
        verify: Whether to verify the exported model using ONNX Runtime. This option
            is only valid when dynamo is True.
        profile: Whether to profile the export process. This option
            is only valid when dynamo is True.
        dump_exported_program: Whether to dump the :class:`torch.export.ExportedProgram` to a file.
            This is useful for debugging the exporter. This option is only valid when dynamo is True.
        artifacts_dir: The directory to save the debugging artifacts like the report and the serialized
            exported program. This option is only valid when dynamo is True.
        fallback: Whether to fallback to the TorchScript exporter if the dynamo exporter fails.
            This option is only valid when dynamo is True. When fallback is enabled, It is
            recommended to set dynamic_axes even when dynamic_shapes is provided.

        training: Deprecated option. Instead, set the training mode of the model before exporting.
        operator_export_type: Deprecated option. Only ONNX is supported.
        do_constant_folding: Deprecated option.
        custom_opsets: Deprecated.
            A dictionary:

            * KEY (str): opset domain name
            * VALUE (int): opset version

            If a custom opset is referenced by ``model`` but not mentioned in this dictionary,
            the opset version is set to 1. Only custom opset domain name and version should be
            indicated through this argument.
        export_modules_as_functions: Deprecated option.

            Flag to enable
            exporting all ``nn.Module`` forward calls as local functions in ONNX. Or a set to indicate the
            particular types of modules to export as local functions in ONNX.
            This feature requires ``opset_version`` >= 15, otherwise the export will fail. This is because
            ``opset_version`` < 15 implies IR version < 8, which means no local function support.
            Module variables will be exported as function attributes. There are two categories of function
            attributes.

            1. Annotated attributes: class variables that have type annotations via
            `PEP 526-style <https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations>`_
            will be exported as attributes.
            Annotated attributes are not used inside the subgraph of ONNX local function because
            they are not created by PyTorch JIT tracing, but they may be used by consumers
            to determine whether or not to replace the function with a particular fused kernel.

            2. Inferred attributes: variables that are used by operators inside the module. Attribute names
            will have prefix "inferred::". This is to differentiate from predefined attributes retrieved from
            python module annotations. Inferred attributes are used inside the subgraph of ONNX local function.

            * ``False`` (default): export ``nn.Module`` forward calls as fine grained nodes.
            * ``True``: export all ``nn.Module`` forward calls as local function nodes.
            * Set of type of nn.Module: export ``nn.Module`` forward calls as local function nodes,
                only if the type of the ``nn.Module`` is found in the set.
        autograd_inlining: Deprecated.
            Flag used to control whether to inline autograd functions.
            Refer to https://github.com/pytorch/pytorch/pull/74765 for more details.

    Returns:
        :class:`torch.onnx.ONNXProgram` if dynamo is True, otherwise None.

    .. versionchanged:: 2.6
        *training* is now deprecated. Instead, set the training mode of the model before exporting.
        *operator_export_type* is now deprecated. Only ONNX is supported.
        *do_constant_folding* is now deprecated. It is always enabled.
        *export_modules_as_functions* is now deprecated.
        *autograd_inlining* is now deprecated.
    .. versionchanged:: 2.7
        *optimize* is now True by default.
    Tr   _compat)rH   rI   rJ   rK   rL   rM   )r5   r6   r7   r8   r9   r:   r@   r;   r<   r>   r?   rA   rB   rC   rD   rE   rF   rG   legacy_export_kwargsN)r   a.  You are using the legacy TorchScript-based ONNX export. Starting in PyTorch 2.9, the new torch.export-based ONNX exporter will be the default. To switch now, set dynamo=True in torch.onnx.export. This new exporter supports features like exporting LLMs with DynamicCache. We encourage you to try it and share feedback to help improve the experience. Learn more about the new export logic: https://pytorch.org/docs/stable/onnx_dynamo.html. For exporting control flow: https://pytorch.org/tutorials/beginner/onnx/export_control_flow_model_to_onnx_tutorial.html.   )category
stacklevelz[The exporter only supports dynamic shapes through parameter dynamic_axes when dynamo=False.)r5   r6   r7   r8   r9   r:   r;   r<   rH   rI   rJ   rK   rL   rM   )
isinstancetorchr   ExportedProgramtorch.onnx._internal.exporterrU   Tensorexport_compatwarningsZtorch.onnx.utilswarnDeprecationWarning
ValueError) rP   rQ   rR   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rU   rV   r`   r   r3   r3   A/var/www/auris/lib/python3.9/site-packages/torch/onnx/__init__.pyr   s   s     x	r   zktorch.onnx.dynamo_export is deprecated since 2.7.0. Please use torch.onnx.export(..., dynamo=True) instead.c                   @  s$   e Zd ZdZddddddZdS )r    a  Options for dynamo_export.

    .. deprecated:: 2.7
        Please use ``torch.onnx.export(..., dynamo=True)`` instead.

    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.
    Nr?   rO   c                C  s
   || _ d S Nre   )selfr?   r3   r3   rd   __init__  s    zExportOptions.__init__)__name__
__module____qualname____doc__rh   r3   r3   r3   rd   r      s   r    )export_optionsz9torch.nn.Module | Callable | torch.export.ExportedProgramzExportOptions | Noner!   )rP   rm   rS   c         	      O  s   ddl }ddlm} ddlm} t| tjjrH|j	| |d|dddddS |dur^|j
dtd	 |dur|jrd
d }|||}nd}|j	| |d||ddddd	S )a  Export a torch.nn.Module to an ONNX graph.

    .. deprecated:: 2.7
        Please use ``torch.onnx.export(..., dynamo=True)`` instead.

    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.
    r   NrT   )_pytree   T)rR   r5   r:   r>   r6   rG   zYou are using an experimental ONNX export logic, which currently only supports dynamic shapes. For a more comprehensive set of export options, including advanced features, please consider using `torch.onnx.export(..., dynamo=True)`. )rX   c                 S  sB   t | tjr:t| j}i }t|D ]}tjjj||< q"|S d S d S rf   )	rZ   r[   r^   lenshaperanger   ZDimZAUTO)xZrankZdynamic_shapeir3   r3   rd   _to_dynamic_shape  s    
z(dynamo_export.<locals>._to_dynamic_shape)rR   r5   r?   r:   r>   r6   rG   )r`   r]   rU   Ztorch.utilsrn   rZ   r[   r   r\   r_   ra   rb   r?   Ztree_map)	rP   rm   Z
model_argsZmodel_kwargsr`   rU   rn   ru   r?   r3   r3   rd   r"     sJ    
r"   )rS   c                  C  s$   ddl m}  ddlm} | jp"|jS )z3Returns whether it is in the middle of ONNX export.r   )GLOBALS)_flags)Ztorch.onnx._globalsrv   r]   rw   Zin_onnx_exportZ_is_onnx_exporting)rv   rw   r3   r3   rd   r   $  s    r   )r3   N)H
__future__r   __all__typingr%   r&   r'   Ztyping_extensionsr(   r[   Ztorch._Cr)   Z_C_onnxZtorch._C._onnxr   r   r   Z_internal._exporter_legacyr#   Z _internal.exporter._onnx_programr!   Z_internal.onnxruntimer$   r+   Z_OrtBackendr,   Z_OrtBackendOptionsr-   Z_OrtExecutionProviderZ_type_utilsr   r   r   r   r.   r/   r   r   r    r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   oscollections.abcr0   r1   r2   rj   Zproducer_nameZPRODUCER_VERSIONZproducer_versionZEVALZONNXr   r    r"   r   r3   r3   r3   rd   <module>   s   +	T  J  MO