
    ¯wgM                       d dl mZ g dZd dlmZmZmZmZmZm	Z	 d dl
Z
d dl
m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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&m'Z'm(Z(m)Z) ddl*mZm+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m!Z! ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA e	rd dlBZBde<_C        de=_C        de_C        de_C        de>_C        de?_C        de _C        de@_C        de_C        de_C        de_C        deA_C        de_C        dZDej                  ZF	 	 ddddddddddddddddddej$                  j                  ej                   j                  ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZIdd	 	 	 	 	 ddZJej                  ZLddZMddZN	 ej                  ZP	 ej                  ZRy)    )annotations)(symbolic_helperutilserrors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ExportTypesOperatorExportTypesTrainingModeTensorProtoDataTypeJitScalarTypeexportexport_to_pretty_stringis_in_onnx_exportselect_model_mode_for_exportregister_custom_op_symbolicunregister_custom_op_symbolicdisable_log
enable_logOnnxExporterErrorDiagnosticOptionsExportOptionsONNXProgramONNXRuntimeOptionsOnnxRegistrydynamo_exportenable_fake_modeis_onnxrt_backend_supported)AnyCallable
CollectionMappingSequenceTYPE_CHECKINGN)_C)_onnx)r   r   r      )r   )r+   
OrtBackendOrtBackendOptionsOrtExecutionProvider)r   )r#   )_optimize_graph_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   r   )r$   r%   r&   r'   r(   r*   z
torch.onnxpytorchTF.)kwargsexport_paramsverboseinput_namesoutput_namesopset_versiondynamic_axeskeep_initializers_as_inputsdynamoexternal_datadynamic_shapesreportverifyprofiledump_exported_programartifacts_dirfallbacktrainingoperator_export_typedo_constant_foldingcustom_opsetsexport_modules_as_functionsautograd_inliningc               <   |du s$t        | t        j                  j                        rGddlm} t        |t        j                        r|f}|j                  | |||||||||	|
||||||||      S ddlm} |rt        d       || ||f|||du ||||	|
||||||d y)	a}  Exports a model into ONNX format.

    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 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.
            Only one parameter `dynamic_axes` or `dynamic_shapes` should be set
            at the same time.
        report: Whether to generate a markdown report for the export process.
        verify: Whether to verify the exported model using ONNX Runtime.
        profile: Whether to profile the export process.
        dump_exported_program: Whether to dump the :class:`torch.export.ExportedProgram` to a file.
            This is useful for debugging the exporter.
        artifacts_dir: The directory to save the debugging artifacts like the report and the serialized
            exported program.
        fallback: Whether to fallback to the TorchScript exporter if the dynamo exporter fails.

        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. The exported graph is always optimized.
        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.
    Tr   exporter)r=   r>   r?   r@   rA   rB   rC   rD   rF   rG   rH   rI   rJ   rK   rL   rM   )r   z[The exporter only supports dynamic shapes through parameter dynamic_axes when dynamo=False.)r=   r>   r?   r@   rA   rB   rC   rD   rN   rO   rP   rQ   rR   rS   N)

isinstancetorchr   ExportedProgramtorch.onnx._internalrV   Tensorexport_compattorch.onnx.utils
ValueError)modelargsfr=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   _rV   r   s                                X/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/onnx/__init__.pyr   r      s    V ~E5<<+G+GH1dELL)7D%%'#%'%(C')"7'' & 
 	
, 	,D 
 		
 'tO#%'%(C!5 3'(C/#	
&     )export_optionsc                 ddl }ddlm} ddlm} ddlm} t        | t        j                  j                        r|j                  | |d|dddd      S |j                  r^||j                  d	t        
       |'|j                  rd }|j!                   |       |      }	nd}	|j                  | |d||	dddd	      S ddlm}
  |
| g|d|i|S )a  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.0}
        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")
    r   N)_flagsrU   )_pytree   T)ra   r=   rB   rF   r>   rM   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)`. )categoryc                     dfd} | S )Nr   c                    t        | t        j                        rVt        | j                        }i }t        |      D ]*  }t        j                  j                  d d|       ||<   , dz  |S y )Narg__dim_r4   )rW   rX   r[   lenshaperanger   Dim)xrankdynamic_shapei	arg_orders       rc   _to_dynamic_shapezKdynamo_export.<locals>._to_dynamic_shapes_mapper.<locals>._to_dynamic_shape  ss    !!U\\2"177|(*!&t A/4||/?/?"&ykqc :0M!, "Q	,,#rd    )rx   rw   s    @rc   _to_dynamic_shapes_mapperz0dynamo_export.<locals>._to_dynamic_shapes_mapper  s    	$ )(rd   )ra   r=   rG   rB   rF   r>   rM   )r)   re   )warnings
torch.onnxrg   rZ   rV   torch.utilsrh   rW   rX   r   rY   r\   USE_EXPERIMENTAL_LOGICwarnFutureWarningrG   tree_map%torch.onnx._internal._exporter_legacyr)   )r_   re   
model_argsmodel_kwargsr{   rg   rV   rh   rz   rG   r)   s              rc   r)   r)     s   f !-#%556%% & 	
 		
 
	&	&%MM: '	   %.*G*G)( %--)+N
 "N%%) & 

 
	
 	H

/=
AM
 	
rd   c                 .    t        j                  d       y)zEnables ONNX logging.TNr2   _jit_set_onnx_log_enabledry   rd   rc   r"   r"     s      &rd   c                 .    t        j                  d       y)zDisables ONNX logging.FNr   ry   rd   rc   r!   r!     s      'rd   )ry   N)8r_   zbtorch.nn.Module | torch.export.ExportedProgram | torch.jit.ScriptModule | torch.jit.ScriptFunctionr`   ztuple[Any, ...]ra   zstr | os.PathLike | Noner=   zdict[str, Any] | Noner>   boolr?   zbool | Noner@   Sequence[str] | NonerA   r   rB   z
int | NonerC   zDMapping[str, Mapping[int, str]] | Mapping[str, Sequence[int]] | NonerD   r   rE   r   rF   r   rG   z3dict[str, Any] | tuple[Any, ...] | list[Any] | NonerH   r   rI   r   rJ   r   rK   r   rL   zstr | os.PathLikerM   r   rN   z_C_onnx.TrainingModerO   z_C_onnx.OperatorExportTypesrP   r   rQ   zMapping[str, int] | NonerR   z(bool | Collection[type[torch.nn.Module]]rS   r   rb   r,   returnz
Any | None)r_   z9torch.nn.Module | Callable | torch.export.ExportedProgramre   zExportOptions | Noner   zONNXProgram | Any)r   None)S
__future__r   __all__typingr,   r-   r.   r/   r0   r1   rX   r2   torch._Cr3   _C_onnxtorch._C._onnxr   r   r   _exporter_statesr   _internal.onnxruntimer+   r5   _OrtBackendr6   _OrtBackendOptionsr7   _OrtExecutionProvider_type_utilsr   r   r#   r   r8   r9   r:   r   r   r   r   r     r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   _internal._exporter_legacyr$   r%   r&   r'   r(   r*   os
__module__producer_namePRODUCER_VERSIONproducer_versionEVALONNXr   r)   _jit_is_onnx_log_enabledis_onnx_log_enabledr"   r!   _jit_set_onnx_log_output_streamset_log_stream_jit_onnx_loglogry   rd   rc   <module>r      s   "0d O N   % Q Q )  ' %	 	 	    ,    ,  ' % ' %  ,  +  & %  ,  #/   *  )5  &++  "&A %)(,)- $ (-JN"''*%,%9%9%>%>8?8S8S8X8X $.2LQ"EAA
 A  A "A A A &A 'A AA" "&#A$ %A( )A* H+A, -A. /A0 1A2  3A4 %5A6 7A: #;A< 6=A> ?A@ ,AAB "JCAD EAF 
GAH IAP ,0	z
Dz
 )	z
 z
@ 11 '
(
 33 	rd   