
    iH=                       d dl mZ g dZd dlmZmZ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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mZmZ ddlmZ erd dl Z d dl!m"Z"m#Z#m$Z$ de_%        de_%        dZ&e
jN                  Z(	 	 dddddddddddddddddddde
j                  jR                  e
j                  jT                  ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ+ddZ,y)    )annotations)errorsopsexportis_in_onnx_exportOnnxExporterErrorONNXProgram)AnyCallableTYPE_CHECKINGN)_onnx)OperatorExportTypesTensorProtoDataTypeTrainingMode   )r   r   )r	   )symbolic_helpersymbolic_opset10symbolic_opset9utils)JitScalarType)register_custom_op_symbolicselect_model_mode_for_exportunregister_custom_op_symbolic)r   )
CollectionMappingSequencez
torch.onnxpytorchTF.)kwargsverboseinput_namesoutput_namesopset_versiondynamoexternal_datadynamic_shapescustom_translation_tablereportoptimizeverifyprofiledump_exported_programartifacts_dirfallbackexport_paramskeep_initializers_as_inputsdynamic_axestrainingoperator_export_typedo_constant_foldingcustom_opsetsexport_modules_as_functionsautograd_inliningc                  |du s$t        | t        j                  j                        rSddlm} t        |t        j                        r|f}||||||d}|j                  | ||||||||||||	|
||||||||      S ddl}ddl	m} |j                  d	t        d
       |
rt        d       || ||f|||du |||||||||||d y)aA#  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 and default 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``.

    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". This argument is kept for
            backward compatibility. It is recommended to leave unspecified (None)
            and use the returned :class:`torch.onnx.ONNXProgram` to serialize the model
            to a file instead.
        kwargs: Optional example keyword inputs.
        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. You should set ``opset_version`` according to the supported opset versions
            of the runtime backend or compiler you want to run the exported model with.
            Leave as default (``None``) to use the recommended version, or refer to
            the ONNX operators documentation for more information.
        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.
        export_params: **When ``f`` is specified**: If false, parameters (weights) will not be exported.

            You can also leave it unspecified and use the returned :class:`torch.onnx.ONNXProgram`
            to control how initializers are treated when serializing the model.
        keep_initializers_as_inputs: **When ``f`` is specified**: 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.

            You can also leave it unspecified and use the returned :class:`torch.onnx.ONNXProgram`
            to control how initializers are treated when serializing the model.
        dynamic_axes:
            Prefer specifying ``dynamic_shapes`` when ``dynamo=True`` and when ``fallback``
            is not enabled.

            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
                ...

        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 option.
        export_modules_as_functions: Deprecated option.
        autograd_inlining: Deprecated option.

    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.
    .. versionchanged:: 2.9
        *dynamo* is now True by default.
    Tr   )_compat)r2   r3   r4   r5   r6   r7   )r   r/   r    r!   r"   r#   r'   r1   r0   r%   r&   r(   r)   r*   r+   r,   r-   r.   legacy_export_kwargsNr   )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.)r   r/   r    r!   r"   r#   r1   r0   r2   r3   r4   r5   r6   r7   )
isinstancetorchr   ExportedProgramtorch.onnx._internal.exporterr9   Tensorexport_compatwarnings$_internal.torchscript_exporter.utilswarnDeprecationWarning
ValueError) modelargsfr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r9   r:   rD   r   s                                    M/var/www/html/engine/venv/lib/python3.12/site-packages/torch/onnx/__init__.pyr   r   ;   s;   | ~E5<<+G+GH9dELL)7D !$8#6*+F!2 
 $$'#%'%=%(C')"7'!5- % 
 	
2 	@k ( 	 
	
 D 
 		
 'tO#%'%(C!5 3'(C/#	
&     c                 N    ddl m}  ddlm} |j                  xs | j
                  S )z3Returns whether it is in the middle of ONNX export.r   )_flags)GLOBALS)rA   rO   2torch.onnx._internal.torchscript_exporter._globalsrP   in_onnx_export_is_onnx_exporting)rO   rP   s     rL   r   r   m  s    4J!!>V%>%>>rM   ) N):rI   zbtorch.nn.Module | torch.export.ExportedProgram | torch.jit.ScriptModule | torch.jit.ScriptFunctionrJ   ztuple[Any, ...]rK   zstr | os.PathLike | Noner   zdict[str, Any] | Noner    zbool | Noner!   Sequence[str] | Noner"   rU   r#   z
int | Noner$   boolr%   rV   r&   z3dict[str, Any] | tuple[Any, ...] | list[Any] | Noner'   z4dict[Callable, Callable | Sequence[Callable]] | Noner(   rV   r)   rV   r*   rV   r+   rV   r,   rV   r-   zstr | os.PathLiker.   rV   r/   rV   r0   rV   r1   zDMapping[str, Mapping[int, str]] | Mapping[str, Sequence[int]] | Noner2   z_C_onnx.TrainingModer3   z_C_onnx.OperatorExportTypesr4   rV   r5   zMapping[str, int] | Noner6   z(bool | Collection[type[torch.nn.Module]]r7   rV   returnzONNXProgram | None)rW   rV   )-
__future__r   __all__typingr
   r   r   r?   torch._Cr   _C_onnxtorch._C._onnxr   r   r    r   r    _internal.exporter._onnx_programr	   _internal.torchscript_exporterr   r   r   r   *_internal.torchscript_exporter._type_utilsr   rE   r   r   r   r   oscollections.abcr   r   r   
__module__producer_namePRODUCER_VERSIONproducer_versionEVALONNXr   r   rT   rM   rL   <module>rj      sR   "
 0 /  %   9  
 & == & +   ++  "&o %)(,)- $JN"''*(- %,%9%9%>%>8?8S8S8X8X $.2LQ"Moo
 o  o "o o &o 'o o o o  H!o"#o& 'o( )o* +o, -o.  /o0 %1o2 3o6 7o8 "&9o:;oB #CoD 6EoF GoH ,IoJ "JKoL MoN Ood	?rM   