
    PhW                        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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. d
dl/m0Z0m1Z1 eej0                  jd                  gee!   f   Z3ejh                   G d d             Z5 G d de6      Z7	 d8dZ8ejh                   G d de5e7             Z9dejt                  de;fdZ< G d de6      Z=dddde>dee;   dee;   fdZ?dddde>dee;   dee;   fd Z@	 d9ddd!d"d#d$ed%eed&f   d'eee>ef      d(eee9      d)eeee>ef   ee   f      d*eAd+ee>d&f   d,e,fd-ZBddd.d/e,d$ee>ej                  ej                  f   d0eee>ef      d1eee>e;f      d,df
d2ZEddd3d$ee>ej                  ej                  f   d0eee>ef      d4eee>e;f      d,e,fd5ZFd6ee   d,dfd7ZGy):    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dynamic_dimexportloadregister_dataclasssave   )r   r   r   )r   r   c                   0    e Zd ZU dZeed<   eed<   eed<   y)_ConstraintTargetz{
    This represents input tensor dimensions.  Don't create this
    class directly; instead, use :func:`dynamic_dim`.
    w_tensort_iddimN)__name__
__module____qualname____doc__r   __annotations__int     `C:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/export/__init__.pyr'   r'   E   s    
 M
I	Hr2   r'   c                   ,     e Zd ZdZd Z	 d fd	Z xZS )_ConstraintFactoryzN
    Metaclass that ensures a private constructor for :class:`Constraint`
    c                 L    t        | j                   d| j                   d      )N.zO has no public constructor. Please use torch.export.dynamic_dim() to create one)	TypeErrorr,   r-   )clsargskwargss      r3   __call__z_ConstraintFactory.__call__W   s2    ~~a 0 01 2B C
 	
r2   c                 ,    t         |   ||||||      S N)superr<   )r9   r(   r)   r*   constraint_rangeshared
debug_name	__class__s          r3   _createz_ConstraintFactory._create]   s%     wdC!16:
 	
r2   NN)r+   r,   r-   r.   r<   rD   __classcell__)rC   s   @r3   r5   r5   R   s    
 MQ
 
r2   r5   c                 6    t         j                  | |||||      S r>   )r   rD   )r(   r)   r*   r@   rA   rB   s         r3   _create_constraintrH   e   s      hc3CVZXXr2   c                       e Zd ZU dZded<   dZee   ed<   dZee	   ed<   de
j                  fdZd	 Zd
 Zd Zd Zd Zed        Zd Zy)r   z

    .. warning::
        Do not construct :class:`Constraint` directly, use :func:`dynamic_dim` instead.

    This represents constraints on input tensor dimensions, e.g., requiring
    them to be fully polymorphic or within some range.

    r   r@   NrA   rB      c                     ddl m} ddlm}  || j                  j
                   |||      z  d      }t        | j                  | j                  | j                  || j                  | j                        S )Nr   r   )ValueRanges)lowerupperFvr	warn_only)%torch.fx.experimental.symbolic_shapesr   torch.utils._sympy.value_rangesrL   r@   rP   rH   r(   r)   r*   rA   rB   )selfrM   rN   r   rL   r@   s         r3   _clone_with_rangezConstraint._clone_with_range~   sf    P?1$$''+E*OO
 "MMIIHHKKOO
 	
r2   c                 &    | j                  |      S )NrM   rU   rT   rM   s     r3   __ge__zConstraint.__ge__       %%E%22r2   c                 ,    | j                  |dz         S )Nr%   rW   rX   rY   s     r3   __gt__zConstraint.__gt__       %%EAI%66r2   c                 &    | j                  |      S )NrN   rX   rT   rN   s     r3   __le__zConstraint.__le__   r[   r2   c                 ,    | j                  |dz
        S )Nr%   r`   rX   ra   s     r3   __lt__zConstraint.__lt__   r^   r2   c                     t        d      )NzCannot determine truth value of Constraint. If you are trying to combine Constraint's with logical connectives, you can specify them separately instead.)r8   rT   s    r3   __bool__zConstraint.__bool__   s    
 7
 	
r2   c                 (   | j                   | j                  | j                  j                  j                  | j                  j                  j
                  | j                  d dS | j                  j                   | j                  j                  ddS )N)r)   r*   )r)   r*   minmaxrA   )r)   r*   r@   rP   rM   rN   rA   rf   s    r3   serializable_speczConstraint.serializable_spec   s     II88((++11((++11 ;;& 
 	
 !KK,,;;??
 	
r2   c                    t        |t              st        dt        |       d      ddlm}  || j                  j                  |j                  j                  z  d      }| j                  |j                  }n3|j                  | j                  |j                  k(  sJ | j                  }t        | j                  | j                  | j                  |t        |j                  |j                  |j                        |      S )NzPA dynamic dim can be specified equal only to another dynamic dim. Equality with z is not supported.r   r   FrO   )rA   rB   )
isinstancer   r8   typerR   r   r@   rP   rB   rH   r(   r)   r*   r'   )rT   otherr   r@   rB   s        r3   __eq__zConstraint.__eq__   s    %,!!%e-?A  	Q1$$''%*@*@*C*CC
 ??"))J##+t%BRBR/RRRJ!MMIIHH$U^^UZZK!
 	
r2   )r+   r,   r-   r.   r/   rA   r
   r'   rB   strmathinfrU   rZ   r]   rb   rd   rg   propertyrk   rp   r1   r2   r3   r   r   k   so     /. +/FH&'. $J$&'txx 
$3737	
 
 
.
r2   r   )	metaclasstindexc                      ddl m}  || |      S )a"
  
    .. warning::
        (This feature is DEPRECATED. See :func:`Dim` instead.)

    :func:`dynamic_dim` constructs a :class:`Constraint` object that describes the dynamism of
    a dimension ``index`` of tensor ``t``. :class:`Constraint` objects should be passed to
    ``constraints`` argument of :func:`export`.

    Args:
        t (torch.Tensor): Example input tensor that have dynamic dimension size(s)
        index (int): Index of dynamic dimension

    Returns:
        A :class:`Constraint` object that describes shape dynamism. It can be passed to :func:`export` so
        that :func:`export` does not assume static size of specified tensor, i.e. keeping it dynamic
        as a symbolic size rather than specializing according to size of example tracing input.

    Specifically :func:`dynamic_dim` can be used to express following types of dynamism.

    - Size of a dimension is dynamic and unbounded::

        t0 = torch.rand(2, 3)
        t1 = torch.rand(3, 4)

        # First dimension of t0 can be dynamic size rather than always being static size 2
        constraints = [dynamic_dim(t0, 0)]
        ep = export(fn, (t0, t1), constraints=constraints)

    - Size of a dimension is dynamic with a lower bound::

        t0 = torch.rand(10, 3)
        t1 = torch.rand(3, 4)

        # First dimension of t0 can be dynamic size with a lower bound of 5 (inclusive)
        # Second dimension of t1 can be dynamic size with a lower bound of 2 (exclusive)
        constraints = [
            dynamic_dim(t0, 0) >= 5,
            dynamic_dim(t1, 1) > 2,
        ]
        ep = export(fn, (t0, t1), constraints=constraints)

    - Size of a dimension is dynamic with an upper bound::

        t0 = torch.rand(10, 3)
        t1 = torch.rand(3, 4)

        # First dimension of t0 can be dynamic size with a upper bound of 16 (inclusive)
        # Second dimension of t1 can be dynamic size with a upper bound of 8 (exclusive)
        constraints = [
            dynamic_dim(t0, 0) <= 16,
            dynamic_dim(t1, 1) < 8,
        ]
        ep = export(fn, (t0, t1), constraints=constraints)

    - Size of a dimension is dynamic and it is always equal to size of another dynamic dimension::

        t0 = torch.rand(10, 3)
        t1 = torch.rand(3, 4)

        # Sizes of second dimension of t0 and first dimension are always equal
        constraints = [
            dynamic_dim(t0, 1) == dynamic_dim(t1, 0),
        ]
        ep = export(fn, (t0, t1), constraints=constraints)

    - Mix and match all types above as long as they do not express conflicting requirements

    r   )r    )torch._exportr    )rv   rw   r    s      r3   r    r       s    J *q%  r2   c                        e Zd ZdZed        Zy)_Dimz*
    Metaclass for :func:`Dim` types.
    c                     |dk(  rd }|t         j                  dz
  k(  rd }||d|  dS |	d|  d| dS |	d|  d| dS d|  d| d| dS )	NrJ   r%   zDim('z')z', max=)z', min=, max=)sysmaxsize)namemin_max_s      r3   readablez_Dim.readable+  s    19D3;;?"D<DL4&##<4&vQ//<4&vQ//tfGD6vQ77r2   N)r+   r,   r-   r.   staticmethodr   r1   r2   r3   r{   r{   &  s     8 8r2   r{   ri   rj   r   ri   rj   c                z   |dnt        j                  |d      }|t        j                  dz
  n&t        j                  |t        j                  dz
        }||kD  sJ d| d|        t        | t        f||d      }t        t        j                  t        j                         d   d         dd      |_        |S )	an  
    :func:`Dim` constructs a type analogous to a named symbolic integer with a range.
    It can be used to describe multiple possible values of a dynamic tensor dimension.
    Note that different dynamic dimensions of the same tensor, or of different tensors,
    can be described by the same type.

    Args:
        name (str): Human-readable name for debugging.
        min (Optional[int]): Minimum possible value of given symbol (inclusive)
        max (Optional[int]): Maximum possible value of given symbol (inclusive)

    Returns:
        A type that can be used in dynamic shape specifications for tensors.
    rJ   r%   z(Cannot create Dim with inconsistent min=r~   r   r   r+   __main__)builtinsrj   r   r   ri   r{   r0   getattrinspect	getmodulestackr,   )r   ri   rj   _min_maxr*   s         r3   r   r   :  s     1c1!5D!k3;;?x||Cq/QD$;SB3%vcUSS;
tcVT$7
8C'--/!,Q/0*jCN Jr2   namesc                 0     t         fd|D              S )z4
    Util to create multiple :func:`Dim` types.
    c              3   :   K   | ]  }t        |         yw)r   N)r   ).0r   rj   ri   s     r3   	<genexpr>zdims.<locals>.<genexpr>W  s     ?Ts,,s   )tuple)ri   rj   r   s   `` r3   r   r   S  s     ????r2   Tr1   )constraintsdynamic_shapesstrictpreserve_module_call_signaturefr:   .r;   r   r   r   r   returnc                N    ddl m}m} | || |||||      S  || |||||      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:
        f: The callable to trace.

        args: Example positional inputs.

        kwargs: Optional example keyword inputs.

        constraints: [DEPRECATED: use ``dynamic_shapes`` instead, see below]
         An optional list of constraints on the dynamic arguments
         that specify their possible range of shapes. By default, shapes of
         input torch.Tensors are assumed to be static. If an input torch.Tensor
         is expected to have dynamic shapes, please use :func:`dynamic_dim`
         to define :class:`Constraint` objects that specify the dynamics and the possible
         range of shapes. See :func:`dynamic_dim` docstring for examples on
         how to use it.

        dynamic_shapes: 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   )r!   export__RC__)r   r   )r   r   r   )ry   r!   r   )	r   r:   r;   r   r   r   r   r!   r   s	            r3   r!   r!   Z  sN    P 3+I
 	
 )+I
 	
r2   extra_filesopset_versionepr   r   c                (    ddl m}  || |||       y)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, pathlib.Path, 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)

    r   )r$   r   N)ry   r$   )r   r   r   r   r$   s        r3   r$   r$     s    h #QK}Er2   r   expected_opset_versionr   c                $    ddl m}  || ||      S )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, pathlib.Path, 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)))
    r   )r"   r   )ry   r"   )r   r   r   r"   s       r3   r"   r"     s    f #	{;Q r2   r9   c                     ddl m}  ||       S )a  
    Registers a dataclass as a valid input/output type for :func:`torch.export.export`.

    Args:
        cls: the dataclass type to register

    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_node)torch._export.utilsr   )r9   r   s     r3   r#   r#   K  s    : F,S11r2   rE   r>   )Hr   copydataclassesr   iorr   pathlibr   typingenumr   r   r   r   r   r   r	   r
   r   r   r   r   torchtorch.fx._pytreefx_pytree	fx_pytreetorch.utils._pytreeutilspytreetorch.fx._compatibilityr   torch.fx.passes.infra.pass_baser   "torch.fx.passes.infra.pass_managerr   r   r   r   r   rR   r   __all__exported_programr   r   r   graph_signaturer   r   GraphModulePassType	dataclassr'   rn   r5   rH   r   Tensorr0   r    r{   rq   r   r   boolr!   PathBytesIOr$   r"   r#   r1   r2   r3   <module>r      s       	   
      $ $ $ $ 1 6 :   M" T S J UXX))*HZ,@@A 	 	 	
 
( DHY m
".@ m
 m
`G!5<< G! G!T84 8( ,0d c 8C= hsm 2 ,0d @ @8C= @hsm @ (,{

 /3BF68{
{

S/{
 T#s(^${

 $z*+{
 U4S>5:#=>?{
 {
 %*#s(O{
 {
D -1.26F6FS',,

*+6F $sCx.)	6F
 DcN+6F 
6Fx -17;	7S',,

*+7 $sCx.)7 %T#s(^4	7
 7t2DI 2$ 2r2   