
    ǄgN                        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Zd dl	Z	d dl
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mZ d dlZd dlmc mZ d dlmZ d dlmZ d dl m!Z! d dlm"Z"m#Z#m$Z$m%Z% erd dl&m'Z' g d	Z(d
dl)m*Z*m+Z+m,Z,m-Z- d
dl.m/Z/m0Z0m1Z1 d
dl2m3Z3m4Z4 d
dl5m6Z6m5Z5m7Z7 eejp                  jr                  gee   f   Z:	 d)dddddejv                  jx                  deedf   deee=ef      deeee=ef   ee   ee   f      de>dee=df   de/fdZ?	 d)dddddejv                  jx                  deedf   deee=ef      deeee=ef   ee   ee   f      de>dee=df   de/fdZ@dddde/dee=ej                  ej                  f   deee=ef      d eee=eCf      ddf
d!ZDddd"dee=ej                  ej                  f   deee=ef      d#eee=eCf      de/fd$ZEdd%d&ee   d'ee=   ddfd(ZFy)*    N)autoEnum)
AnyCallableDictIteratorListOptionalTupleTypeTYPE_CHECKINGUnion)compatibility)
PassResult)PassManager)FlattenFuncFromDumpableContextFnToDumpableContextFnUnflattenFunc)StrictMinMaxConstraint)
ConstraintDimExportBackwardSignatureExportGraphSignatureExportedProgramModuleCallEntryModuleCallSignaturedimsexportexport_for_trainingloadregister_dataclasssave	unflattenFlatArgsAdapterUnflattenedModule   )r   r   r   ShapesCollection)r   r   r   )r   r   )r%   r$   r&   T )dynamic_shapesstrictpreserve_module_call_signaturemodargs.kwargsr*   r+   r,   returnc                    ddl m} t        | t        j                  j
                        st        dt        |        d      t        | t        j                  j                        rt        d       || |||||      S )aB  
    :func:`export_for_training` takes any nn.Module along with example inputs, and produces a traced graph representing
    only the Tensor computation of the function in an Ahead-of-Time (AOT) fashion,
    which can subsequently be executed with different inputs or serialized. The
    traced graph (1) produces normalized operators in the all ATen operator set
    (as well as any user-specified custom operators), (2) has eliminated all Python control
    flow and data structures (with certain exceptions), and (3) records the set of
    shape constraints needed to show that this normalization and control-flow elimination
    is sound for future inputs. This API is intended for PT2 quantization training use cases
    and will soon be the default IR of torch.export.export in the near future.

    **Soundness Guarantee**

    See :func:`export()` docstring for more details.

    Args:
        mod: We will trace the forward method of this module.

        args: Example positional inputs.

        kwargs: Optional example keyword inputs.

        dynamic_shapes:
         An optional argument where the type should either be:
         1) a dict from argument names of ``f`` to their dynamic shape specifications,
         2) a tuple that specifies dynamic shape specifications for each input in original order.
         If you are specifying dynamism on keyword args, you will need to pass them in the order that
         is defined in the original function signature.

         The dynamic shape of a tensor argument can be specified as either
         (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is
         not required to include static dimension indices in this dict, but when they are,
         they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None,
         where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions
         are denoted by None. Arguments that are dicts or tuples / lists of tensors are
         recursively specified by using mappings or sequences of contained specifications.

        strict: When enabled (default), the export function will trace the program through
         TorchDynamo which will ensure the soundness of the resulting graph. Otherwise, the
         exported program will not validate the implicit assumptions baked into the graph and
         may cause behavior divergence between the original model and the exported one. This is
         useful when users need to workaround bugs in the tracer, or simply want incrementally
         enable safety in their models. Note that this does not affect the resulting IR spec
         to be different and the model will be serialized in the same way regardless of what value
         is passed here.
         WARNING: This option is experimental and use this at your own risk.

    Returns:
        An :class:`ExportedProgram` containing the traced callable.

    **Acceptable input/output types**

    Acceptable types of inputs (for ``args`` and ``kwargs``) and outputs include:

    - Primitive types, i.e. ``torch.Tensor``, ``int``, ``float``, ``bool`` and ``str``.
    - Dataclasses, but they must be registered by calling :func:`register_dataclass` first.
    - (Nested) Data structures comprising of ``dict``, ``list``, ``tuple``, ``namedtuple`` and
      ``OrderedDict`` containing all above types.

    r'   )_export_for_training;Expected `mod` to be an instance of `torch.nn.Module`, got .Exporting a ScriptModule is not supported. Maybe try converting your ScriptModule to an ExportedProgram using `TS2EPConverter(mod, args, kwargs).convert()` instead.)r+   r,   )
_tracer2   
isinstancetorchnnModule
ValueErrortypejitScriptModule)r-   r.   r/   r*   r+   r,   r2   s          ]/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/export/__init__.pyr    r    I   s    J -c588??+I$s)TUV
 	
 #uyy--.K
 	

  'E     c          	         ddl m} t        | t        j                  j
                        st        dt        |        d      t        | t        j                  j                        rt        d       || |||||d      S )a  
    :func:`export` takes an arbitrary Python callable (an nn.Module, a function or
    a method) along with example inputs, and produces a traced graph representing
    only the Tensor computation of the function in an Ahead-of-Time (AOT) fashion,
    which can subsequently be executed with different inputs or serialized.  The
    traced graph (1) produces normalized operators in the functional ATen operator set
    (as well as any user-specified custom operators), (2) has eliminated all Python control
    flow and data structures (with certain exceptions), and (3) records the set of
    shape constraints needed to show that this normalization and control-flow elimination
    is sound for future inputs.

    **Soundness Guarantee**

    While tracing, :func:`export()` takes note of shape-related assumptions
    made by the user program and the underlying PyTorch operator kernels.
    The output :class:`ExportedProgram` is considered valid only when these
    assumptions hold true.

    Tracing makes assumptions on the shapes (not values) of input tensors.
    Such assumptions must be validated at graph capture time for :func:`export`
    to succeed. Specifically:

    - Assumptions on static shapes of input tensors are automatically validated without additional effort.
    - Assumptions on dynamic shape of input tensors require explicit specification
      by using the :func:`Dim` API to construct dynamic dimensions and by associating
      them with example inputs through the ``dynamic_shapes`` argument.

    If any assumption can not be validated, a fatal error will be raised. When that happens,
    the error message will include suggested fixes to the specification that are needed
    to validate the assumptions. For example :func:`export` might suggest the
    following fix to the definition of a dynamic dimension ``dim0_x``, say appearing in the
    shape associated with input ``x``, that was previously defined as ``Dim("dim0_x")``::

        dim = Dim("dim0_x", max=5)

    This example means the generated code requires dimension 0 of input ``x`` to be less
    than or equal to 5 to be valid. You can inspect the suggested fixes to dynamic dimension
    definitions and then copy them verbatim into your code without needing to change the
    ``dynamic_shapes`` argument to your :func:`export` call.

    Args:
        mod: We will trace the forward method of this module.

        args: Example positional inputs.

        kwargs: Optional example keyword inputs.

        dynamic_shapes:
         An optional argument where the type should either be:
         1) a dict from argument names of ``f`` to their dynamic shape specifications,
         2) a tuple that specifies dynamic shape specifications for each input in original order.
         If you are specifying dynamism on keyword args, you will need to pass them in the order that
         is defined in the original function signature.

         The dynamic shape of a tensor argument can be specified as either
         (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is
         not required to include static dimension indices in this dict, but when they are,
         they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None,
         where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions
         are denoted by None. Arguments that are dicts or tuples / lists of tensors are
         recursively specified by using mappings or sequences of contained specifications.

        strict: When enabled (default), the export function will trace the program through
         TorchDynamo which will ensure the soundness of the resulting graph. Otherwise, the
         exported program will not validate the implicit assumptions baked into the graph and
         may cause behavior divergence between the original model and the exported one. This is
         useful when users need to workaround bugs in the tracer, or simply want incrementally
         enable safety in their models. Note that this does not affect the resulting IR spec
         to be different and the model will be serialized in the same way regardless of what value
         is passed here.
         WARNING: This option is experimental and use this at your own risk.

    Returns:
        An :class:`ExportedProgram` containing the traced callable.

    **Acceptable input/output types**

    Acceptable types of inputs (for ``args`` and ``kwargs``) and outputs include:

    - Primitive types, i.e. ``torch.Tensor``, ``int``, ``float``, ``bool`` and ``str``.
    - Dataclasses, but they must be registered by calling :func:`register_dataclass` first.
    - (Nested) Data structures comprising of ``dict``, ``list``, ``tuple``, ``namedtuple`` and
      ``OrderedDict`` containing all above types.

    r'   )_exportr3   r4   r5   T)r+   r,   pre_dispatch)
r6   rB   r7   r8   r9   r:   r;   r<   r=   r>   )r-   r.   r/   r*   r+   r,   rB   s          r?   r   r      s    |  c588??+I$s)TUV
 	
 #uyy--.K
 	

 'E r@   )extra_filesopset_versionepfrD   rE   c          
      L   t        | t              s"t        dt        |       j                   d      ddlm} ddlm}m	}  || |      }t        |t        t        j                  f      rt        j                  |      }t        j                  |d      5 }t        |j                   t"              sJ |j%                  d|j                          |j%                  d|j&                         |j%                  d	|j(                         |j%                  d
|j*                         |j%                  ddj-                  t/        t        |                   |r>|j1                         D ]+  \  }	}
|
j3                  d      }|j%                  d|	 |       - ddd       y# 1 sw Y   yxY w)a"  

    .. warning::
        Under active development, saved files may not be usable in newer versions
        of PyTorch.

    Saves an :class:`ExportedProgram` to a file-like object. It can then be
    loaded using the Python API :func:`torch.export.load <torch.export.load>`.

    Args:
        ep (ExportedProgram): The exported program to save.

        f (Union[str, os.PathLike, io.BytesIO): A file-like object (has to
         implement write and flush) or a string containing a file name.

        extra_files (Optional[Dict[str, Any]]): Map from filename to contents
         which will be stored as part of f.

        opset_version (Optional[Dict[str, int]]): A map of opset names
         to the version of this opset


    Example::

        import torch
        import io

        class MyModule(torch.nn.Module):
            def forward(self, x):
                return x + 10

        ep = torch.export.export(MyModule(), (torch.randn(5),))

        # Save to file
        torch.export.save(ep, 'exported_program.pt2')

        # Save to io.BytesIO buffer
        buffer = io.BytesIO()
        torch.export.save(ep, buffer)

        # Save with extra files
        extra_files = {'foo.txt': b'bar'.decode('utf-8')}
        torch.export.save(ep, 'exported_program.pt2', extra_files=extra_files)

    zBThe 'ep' parameter must be an instance of 'ExportedProgram', got 'z
' instead.r   SCHEMA_VERSION)	serializeSerializedArtifactw serialized_exported_program.jsonserialized_state_dict.ptserialized_constants.ptserialized_example_inputs.ptversionr4   utf-8zextra_files/N)r7   r   	TypeErrorr<   __name__torch._export.serde.schemarJ   torch._export.serde.serializerK   rL   strosPathLikefspathzipfileZipFileexported_programbyteswritestr
state_dict	constantsexample_inputsjoinmapitemsencode)rF   rG   rD   rE   rJ   rK   rL   artifactzipfextra_file_namecontentencoded_contents               r?   r#   r#     sd   h b/*PQUVXQYQbQbPccmn
 	
 :K#,R#?H!c2;;'(IIaL	C	  QD(33U;;;8(:S:ST0(2E2EF/1C1CD4h6M6MNi#c>*B!CD ,7,=,=,? Q(").."9_,=>PQQ Q Qs   C<FF#)rD   expected_opset_versionrm   c                P   t        | t        t        j                  f      rt        j                  |       } |xs i }t        j                  | d      5 }|j                  d      j                         j                  d      }ddl
m} t        |      t        |      k(  sJ |d   t        |d         k7  rt        d| d| d      ddlm}m} d	}d	}	d	}
d	}|j#                         D ]  }|j                  |j$                        }|j$                  d
k(  r|}1|j$                  dk(  rt'        j(                  d       |}	X|j$                  dk(  rt'        j(                  d       |}
|j$                  dk(  r|}	|j$                  dk(  r|}
|j$                  dk(  r|}|j$                  j+                  d      s|j$                  j                  dd      d   }|j                  d      ||<    |J |	J |
J |J  |||	|
|      } |||      }|cd	d	d	       S # 1 sw Y   y	xY w)a  

    .. warning::
        Under active development, saved files may not be usable in newer versions
        of PyTorch.

    Loads an :class:`ExportedProgram` previously saved with
    :func:`torch.export.save <torch.export.save>`.

    Args:
        ep (ExportedProgram): The exported program to save.

        f (Union[str, os.PathLike, io.BytesIO): A file-like object (has to
         implement write and flush) or a string containing a file name.

        extra_files (Optional[Dict[str, Any]]): The extra filenames given in
         this map would be loaded and their content would be stored in the
         provided map.

        expected_opset_version (Optional[Dict[str, int]]): A map of opset names
         to expected opset versions

    Returns:
        An :class:`ExportedProgram` object

    Example::

        import torch
        import io

        # Load ExportedProgram from file
        ep = torch.export.load('exported_program.pt2')

        # Load ExportedProgram from io.BytesIO object
        with open('exported_program.pt2', 'rb') as f:
            buffer = io.BytesIO(f.read())
        buffer.seek(0)
        ep = torch.export.load(buffer)

        # Load with extra files.
        extra_files = {'foo.txt': ''}  # values will be replaced with data
        ep = torch.export.load('exported_program.pt2', extra_files=extra_files)
        print(extra_files['foo.txt'])
        print(ep(torch.randn(5)))
    rrR   r4   r   rI   zSerialized version z+ does not match our current schema version )deserializerL   NrN   zserialized_state_dict.jsonz"This version of file is deprecatedzserialized_constants.jsonrO   rP   rQ   rD   /r'   rS   )r7   rX   rY   rZ   r[   r\   r]   readdecodesplitrV   rJ   lenRuntimeErrorrW   rp   rL   infolistfilenamewarningswarn
startswith)rG   rD   rm   ri   rR   rJ   rp   rL   serialized_exported_programserialized_state_dictserialized_constantsserialized_example_inputs	file_infofile_contentrx   rh   rF   s                    r?   r!   r!   k  sP   f !c2;;'(IIaL#K	C	  8D))I&--/55c:=7|s>22221:^A.//%gY /""0!14 
 	R 8<#150459! 	EI99Y%7%78L!!%GG.:+##'CCBC(4%##'BBBC'3$##'AA(4%##'@@'3$##'EE,8)##..}=$--33C;A>(4(;(;G(DH%'	E* +666$000#///(444'9'! %	(
 #9:q8 8 8s   E$H7AHH%serialized_type_nameclsr   c                "    ddl m}  || |      S )aV  
    Registers a dataclass as a valid input/output type for :func:`torch.export.export`.

    Args:
        cls: the dataclass type to register
        serialized_type_name: The serialized name for the dataclass. This is
        required if you want to serialize the pytree TreeSpec containing this
        dataclass.

    Example::

        @dataclass
        class InputDataClass:
            feature: torch.Tensor
            bias: int

        class OutputDataClass:
            res: torch.Tensor

        torch.export.register_dataclass(InputDataClass)
        torch.export.register_dataclass(OutputDataClass)

        def fn(o: InputDataClass) -> torch.Tensor:
            res = res=o.feature + o.bias
            return OutputDataClass(res=res)

        ep = torch.export.export(fn, (InputDataClass(torch.ones(2, 2), 1), ))
        print(ep)

    r   )!register_dataclass_as_pytree_noder   )torch._export.utilsr   )r   r   r   s      r?   r"   r"     s    H F,"6 r@   )N)GbuiltinscopydataclassesinspectiorY   systypingry   r\   enumr   r   r   r   r   r   r	   r
   r   r   r   r   r8   torch.utils._pytreeutils_pytreepytreetorch.fx._compatibilityr   torch.fx.passes.infra.pass_baser   "torch.fx.passes.infra.pass_managerr   r   r   r   r   %torch.fx.experimental.symbolic_shapesr   __all__r*   r   r   r   r(   r^   r   r   r   graph_signaturer   r   r$   r%   r&   fxGraphModulePassTyper9   r:   rX   boolr    r   rZ   BytesIOintr#   r!   r"   r)   r@   r?   <module>r      s       	 	 
        $ $ 1 6 :   M( D C S S J D D UXX))*HZ,@@A (,X
 NR68X	X
S/X T#s(^$X
 U4S>5:tCy#HIJX X %*#s(OX X| (,r
 NR68r	r
S/r T#s(^$r
 U4S>5:tCy#HIJr r %*#s(Or rr -1.2OQOQS"++rzz)*OQ $sCx.)	OQ
 DcN+OQ 
OQj -17;	pS"++rzz)*p $sCx.)p %T#s(^4	p
 pl +/(	c( #3-( 
	(r@   