
    Vh*                        d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
mZmZmZmZ d dlZd dlmZmZmZmZmZmZmZmZmZ ddlmZ erd dlmZ d d	lmZ d d
l m!Z!m"Z" g dZ# ejH                  e%      Z& G d de      Z' G d de(      Z) G d de)      Z* G d de)      Z+dddde,dee-   dee-   fdZ.e'j^                  e._/        e'j`                  e._0        e'jb                  e._1        dddde,dee-   dee-   de2e)df   fdZ3e jh                   G d d             Z5e jh                   G d d e5             Z6e jh                   G d! d"             Z7e jh                   G d# d$e5             Z8e jh                   G d% d&e5             Z9ee6e8e9f   Z:d'e:d(ee-e-ge;d)   f   d*d+de<e,e2e-e-f   f   d,e;e2d-      d.e;e2d)ed/   ef      d0e<e,d1f   d2e=d)   fd3Z>dd4d5ede
f   d6e
d7e
d8ee,   de
f
d9Z?dDde<e,e
f   fd:Z@ G d; d<      ZAd= ZBd>e<e,e
f   d7ee<e,e
f   e2e
   e;e
   df   fd?ZCd>e<e,e
f   d7ee<e,e
f   e2e
   e;e
   df   de;e:   fd@ZDd7ee<e,e
f   e2e
   e;e
   df   fdAZEdBe,d7ee<e,e
f   e2e
   e;e
   f   dee<e,e
f   e2e
   e;e
   f   fdCZFy)E    N)defaultdict)autoEnum)AnyCallableOptionalTYPE_CHECKINGUnion)	_get_node_typeBUILTIN_TYPESkeystrLeafSpec
MappingKeySequenceKeySUPPORTED_NODEStree_flattentree_map_with_path   )ExportedProgram)Symbol)Source)ShapeEnvStrictMinMaxConstraint)
ConstraintDimdims*refine_dynamic_shapes_from_suggested_fixesc                   :    e Zd ZdZ e       Z e       Z e       Zy)_DimHintz
    Enum for dynamic shape hints.
    - AUTO means automatic inference of shape (static or dynamic).
    - STATIC means static shape (always specialized).
    - DYNAMIC means dynamic, will error out if specialized.
    N)__name__
__module____qualname____doc__r   AUTOSTATICDYNAMIC     K/home/dcms/DCMS/lib/python3.12/site-packages/torch/export/dynamic_shapes.pyr   r   +   s     6DVFfGr(   r   c                   P    e Zd ZdZed        Zd Zd Zd Zd Z	d Z
d Zd	 Zd
 Zy)_Dimz*
    Metaclass for :func:`Dim` types.
    c                     ddl m} |dk(  rd }||k(  rd }||d|  dS |	d|  d| dS |	d|  d| dS d|  d| d	| dS )
Nr   int_oo   zDim('z')z', max=)z', min=, max=)torch.utils._sympy.numbersr.   )namemin_max_r.   s       r)   readablez_Dim.readable=   s    519D6>D<DL4&##<4&vQ//<4&vQ//tfGD6vQ77r(   c                     t              t        urt        d d| j                   d      | j	                  fd      S )NzAttempted to add z to m, where an integer was expected. (Only increasing linear operations with integer coefficients are supported.)c                     | z   S Nr'   xothers    r)   <lambda>z_Dim.__add__.<locals>.<lambda>T       QY r(   typeintNotImplementedErrorr    _deriveclsr=   s    `r)   __add__z_Dim.__add__M   sK    ;c!%#E7$s||n =_ _  {{.//r(   c                     | |z   S r:   r'   rE   s     r)   __radd__z_Dim.__radd__V       U{r(   c                     t              t        urt        d d| j                   d      | j	                  fd      S )NzAttempted to subtract z from r8   c                     | z
  S r:   r'   r;   s    r)   r>   z_Dim.__sub__.<locals>.<lambda>`   r?   r(   r@   rE   s    `r)   __sub__z_Dim.__sub__Y   sL    ;c!%(vcll^ D_ _  {{.//r(   c                 4    t        d| j                   d      )NzAttempted to negate zN. (Only increasing linear operations with integer coefficients are supported.))rC   r    rE   s     r)   __rsub__z_Dim.__rsub__b   s&    !"3<<. 1[ [
 	
r(   c                     t              t        usdk  rt        d d| j                   d      | j	                  fd      S )Nr   zAttempted to multiply z with zu, where a positive integer was expected. (Only increasing linear operations with integer coefficients are supported.)c                     | z  S r:   r'   r;   s    r)   r>   z_Dim.__mul__.<locals>.<lambda>o   r?   r(   r@   rE   s    `r)   __mul__z_Dim.__mul__h   sR    ;c!UaZ%(vcll^ D_ _  {{.//r(   c                     | |z  S r:   r'   rE   s     r)   __rmul__z_Dim.__rmul__q   rJ   r(   c                 P    ddl m} t         | || j                                    S )Nr   )sympify)sympyrV   strr    )rF   fnrV   s      r)   _derived_namez_Dim._derived_namet   s    !2gcll+,--r(   c                 J    t        | j                  |      t        f| |d      S )NrootrY   )_DerivedDimrZ   rB   )rF   rY   s     r)   rD   z_Dim._derivey   s#    3,,R03&3b:QRRr(   N)r    r!   r"   r#   staticmethodr6   rG   rI   rM   rO   rR   rT   rZ   rD   r'   r(   r)   r+   r+   8   sD     8 800
0.
Sr(   r+   c                   0    e Zd ZdZed        Zed        Zy)
_StaticDimz
    Meta class for static :func:`Dim` types.

    This class is only for setting and checking static dim constraints,
    and the user should never interact with it.
    c                     | j                   S r:   valueselfs    r)   minz_StaticDim.min       zzr(   c                     | j                   S r:   rc   re   s    r)   maxz_StaticDim.max   rh   r(   N)r    r!   r"   r#   propertyrg   rj   r'   r(   r)   ra   ra   }   s/        r(   ra   c                   6    e Zd ZdZed        Zed        Zd Zy)r^   a  
    Metaclass for derived :func:`Dim` types.

    Currently we only support increasing linear expressions with integer coefficients.
    In other words, a derived Dim can always be written in the form Ax + B, where
    x is a regular Dim (i.e., non-derived Dim), A and B are integers, and A is positive.
    (In particular, the latter ensures that x < y => Ax + B < Ay + B.)
    These restrictions on the form of derived Dims makes the metatheory simpler: e.g.,
    it simplifies computing ranges for derived Dims, solving for underlying regular Dims,
    deciding equalities between derived Dims, and so on.

    The function lambda x: Ax + B is expressed by `fn`, where x is a normal Dim, `root`.
    The range of a derived Dim is computed by mapping `fn` over the range of its `root`.
    c                 >   ddl m} ddlm} | j                  j
                  | u r| S | j                   || j                  j
                              }| j                  }|dk\  s/J d| j                   d|j                   d|j
                   d       t        |      S )Nr   Integerr-   zExpected derived min value of z9 to be >= 0. Please specify an appropriate min value for  (currently ).)	rW   ro   r2   r.   r]   rg   rY   r    rB   )rf   ro   r.   _min_symintr]   s        r)   rg   z_DerivedDim.min   s     	"599==VG#7Ngggdiimm45yya 	
,T]]O <;;?==/ J((2'	

 ;r(   c           
         ddl m} ddlm} | j                  j
                  |u r|S | j                   || j                  j
                              }| j                  }|t        j                  dz
  k  sCJ d| j                   dt        j                  dz
   d|j                   d|j
                   d		       t        |      S )
Nr   rn   r-   r   zExpected derived max value of z
 to be <= z.. Please specify an appropriate max value for rp   rq   )rW   ro   r2   r.   r]   rj   rY   sysmaxsizer    rB   )rf   ro   r.   _max_symintr]   s        r)   rj   z_DerivedDim.max   s     	"599==F"Mgggdiimm45yyckkAo- 	
,T]]O:ckkTUoEV W;;?==/ J((2'	
-
 ;r(   c                 j     t         j                        t        f j                   fdd      S )Nc                 2     j                  |             S r:   )rY   )r<   rY   rf   s    r)   r>   z%_DerivedDim._derive.<locals>.<lambda>   s    4771: r(   r\   )r^   rZ   rB   r]   )rf   rY   s   ``r)   rD   z_DerivedDim._derive   s2     r"FYY&>?
 	
r(   N)r    r!   r"   r#   rk   rg   rj   rD   r'   r(   r)   r^   r^      s4        &    &
r(   r^   rg   rj   r3   rg   rj   c                &   ddl m} |dn|}||n|}||kD  sJ d| d|        | j                         s
J 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.
    r   r-   z(Cannot create Dim with inconsistent min=r1   z)Dim name must be a valid identifier, got ry   r   r    __main__)
r2   r.   isidentifierr+   rB   getattrinspect	getmodulestackr!   )r3   rg   rj   r.   _min_maxdims          r)   r   r      s      21D[6cD$;SB3%vcUSS;R"KD6 RR
tcVT$7
8C'--/!,Q/0*jCN Jr(   namesreturn.c                 0     t         fd|D              S )zh
    Util to create multiple :func:`Dim` types.

    Returns:
        A tuple of :func:`Dim` types.
    c              3   :   K   | ]  }t        |         yw)ry   N)r   ).0r3   rj   rg   s     r)   	<genexpr>zdims.<locals>.<genexpr>   s     ?Ts,,?s   )tuple)rg   rj   r   s   `` r)   r   r      s     ????r(   c                   &    e Zd ZU dZeed<   eed<   y)_ConstraintTargetz2
    This represents input tensor dimensions.
    t_idr   N)r    r!   r"   r#   rB   __annotations__r'   r(   r)   r   r      s     I	Hr(   r   c                   \    e Zd ZU dZeed<   ded<   ddZd Zd Zd	 Z	d
 Z
d Zed        Zy)_Constraintz
    This represents a Dim describing a constraint target.

    `name` is the name of the Dim.
    `constraint_range` contains the min/max bounds of the Dim.
    r3   r   constraint_rangeNc                     ddl m} ddlm} ddlm} ||} || j                  j                   |||      z  d      }t        | j                  | j                  | j                  |      S )Nr   r   r-   ValueRangeslowerupperFvr	warn_only)%torch.fx.experimental.symbolic_shapesr   r2   r.   torch.utils._sympy.value_rangesr   r   r   r   r   r   r3   )rf   r   r   r   r.   r   r   s          r)   _clone_with_rangez_Constraint._clone_with_range  se    P5?=E1$$''+E*OO
 IIHHII	
 	
r(   c                 &    | j                  |      S )Nr   r   rf   r   s     r)   __ge__z_Constraint.__ge__)      %%E%22r(   c                 ,    | j                  |dz         S )Nr   r   r   r   s     r)   __gt__z_Constraint.__gt__,      %%EAI%66r(   c                 &    | j                  |      S )Nr   r   rf   r   s     r)   __le__z_Constraint.__le__/  r   r(   c                 ,    | j                  |dz
        S )Nr   r   r   r   s     r)   __lt__z_Constraint.__lt__2  r   r(   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.)	TypeErrorre   s    r)   __bool__z_Constraint.__bool__5  s    
 7
 	
r(   c                     | j                   | j                  | j                  j                  j                  | j                  j                  j
                  dS N)r   r   rg   rj   r   r   r   r   r   r   re   s    r)   serializable_specz_Constraint.serializable_spec@  sF     II88((++11((++11	
 	
r(   )r   N)r    r!   r"   r#   rX   r   r   r   r   r   r   r   rk   r   r'   r(   r)   r   r   	  sF     I..
(3737	
 
 
r(   r   c                   0    e Zd ZU dZeed<   ded<   eed<   y)_PhantomRoota  
    This represents the root of a derived Dim where the root does not directly
    specify the shape of any input dimension, but the derived Dim does.

    e.g., the input shapes 2*dim and dim + 1 are related via a "phantom" dim.

    The fields `name`, `constraint_range`, and `val` carried by a phantom root
    help create a symbol for it. Any derived dims with this phantom root are
    backed by expressions over this symbol.
    r3   r   r   valN)r    r!   r"   r#   rX   r   rB   r'   r(   r)   r   r   Q  s    	 I..	Hr(   r   c                   T    e Zd ZU dZeed<   ded<   eeef   ed<   e	ed<   e
d        Zy)	_DerivedConstraintaC  
    This represents a derived Dim, whose root is either a regular constraint target
    (which directly specifies the shape of some input dimension) or a phantom root
    (which does so indirectly).

    It can be thought of as a subclass of `_Constraint`, except that it does not
    support <, <=, >, >= operations.
    r3   r   r   r]   rY   c                     | j                   | j                  | j                  j                  j                  | j                  j                  j
                  dS r   r   re   s    r)   r   z$_DerivedConstraint.serializable_specs  sF     II88((++11((++11	
 	
r(   N)r    r!   r"   r#   rX   r   r
   r   r   r   rk   r   r'   r(   r)   r   r   c  s<     I..
!</
00L
 
r(   r   c                        e Zd ZdZed        Zy)_RelaxedConstrainta  
    This represents a dim marked with Dim.AUTO/DYNAMIC (i.e. mark_dynamic() or maybe_mark_dynamic()),
    which leaves relations & min/max ranges for inference, instead of requiring explicit specification.
    The intention is for constraint violations to not be raised if produce_guards() finds equalities or
    relations between a _RelaxedConstraint and another type of _Constraint.
    c                 4    | j                   | j                  dS )Nr   r   r   re   s    r)   r   z$_RelaxedConstraint.serializable_spec  s     II88
 	
r(   N)r    r!   r"   r#   rk   r   r'   r(   r)   r   r   ~  s     
 
r(   r   
constraintget_sourcesr   	shape_envr   source_pairs)r   r   derived_equalities)r   r   phantom_symbolsr   relaxed_sourcesc                     || j                   | j                        }|sy|^}	|j                  fd|	D               t        | t              rj| j
                  |v r6|| j
                     \  }
} ||
|      }	|j                  fd|	D               y| j                   | j                  f|| j
                  <   yt        | t              rit        | j                  t              s5 || j                  j                   | j                  j                        d   }n| j                  j
                  |v r|| j                  j
                     }n|j                  | j                  j                  t        j                  j                  j                  | j                  j
                        t        j                  j                   j"                  j$                  j&                  | j                  j(                        }||| j                  j
                  <   | j*                  }|j-                  ||f       yt        | t.              r|j1                         yy)z
    Updates `source_pairs`, `derived_equalities`, and `phantom_symbols` (which become
    fields of `EqualityConstraint`) based on a given input `constraint`.
    Nc              3   &   K   | ]  }|f 
 y wr:   r'   r   other_sourcesources     r)   r   z&_process_equalities.<locals>.<genexpr>  s     Q<.Q   c              3   &   K   | ]  }|f 
 y wr:   r'   r   s     r)   r   z&_process_equalities.<locals>.<genexpr>  s       +7& r   r   )r   r   dynamic_dimconstraint_dim)r   r   extend
isinstancer   r3   r   r]   r   create_symbolr   torch_dynamor   ConstantSourcefxexperimentalsymbolic_shapes
DimDynamicr&   r   rY   appendr   add)r   r   r   r   r   r   r   r   sourcesother_sourcesshared_t_id
shared_dimr]   rY   r   s                 @r)   _process_equalitiesr     s    *//:>>:G$F] Q=QQ*k*??e#&+JOO&<#K'Z@M  ;H   '1ooz~~%FE*//"	J 2	3*//<8z33Z__5H5HI!LD ##6&z';';< !.."++ ==//>>z?S?ST % 5 5 E E P P X X#-??#C#C	 /  9=
 4 45]] 	!!64"45	J 2	3F# 
4r(   	tree_namefunctreedynamic_shapesr   c                0   	
 d  fd	 t        |g|diS # t        $ ri}d|j                  d   v rR|sJ d       sJ d       d 
fd		
fd
	t        |      \  }}|D ]  }t        |      \  }} 	||g          d}~ww xY w)a"  
    Customized tree_map for mapping pytrees to dynamic_shapes.

    For built-in types (e.g., standard collections) this behaves exactly like tree_map.

    OTOH for a user-defined class C registered with pytree, we cannot assume that a C
    containing tensors can be mapped to a C containing dynamic shapes (i.e., C may not
    be a polymorphic container). In that case we use the flattened form of C instead.
    Thus a C(**tensors) that flattens to (**tensors) will map to (**dynamic_shapes).

    Args:
        func: function to apply to each (int, float, str, bool, None, torch.Tensor)
        tree: input pytree
        dynamic_shapes: zero or more (typically one) dynamic_shapes to match

    Returns:
        output pytree mapping func to each (int, float, str, bool, None, torch.Tensor)
    c                 $    t        |       t        vS r:   )r   r   )ts    r)   is_leafz$_tree_map_with_path.<locals>.is_leaf  s    
 a 55r(   c                     t        |      }|t        v r)t        t        |   j                  |      d   g|diS  | |g| S )Nr   r   )r   r   r   
flatten_fn)pathr   r   typfr   r   s       r)   r   z_tree_map_with_path.<locals>.f  sg    Q/! &$//215    	  a1.11r(   r   mismatchr   z2Cannot be a mismatch if there is no dynamic_shapesz7Must provide a tree_name when there might be a mismatchc                     | t         u rt        ||         S | t        t        fv r|J t	        |      S t        d|        )NzDid not expect type )dictr   listr   r   AssertionError)type_contextis      r)   _keyz!_tree_map_with_path.<locals>._key  sK    D=%gaj11T5M)"?*?&q>)$';E7%CDDr(   c                 J    ddl m}m}  ||j                  d d|  d      )Nr   	UserErrorUserErrorTypez,Detected mismatch between the structure of `z` and `dynamic_shapes`: dynamic_shapes_validation	case_name)torch._dynamo.excr   r   INVALID_INPUT)msgr   r   r   s      r)   raise_mismatch_errorz1_tree_map_with_path.<locals>.raise_mismatch_error  s2    F!//B9+Mefiejk9 r(   c                    t        |      }t        | t              ry t        |t              r d | d| j                   d| d       | j                  |j                  k7  r* d | d| j                   d| d|j                   	       t	        | j
                        t	        |j
                        k7  r= d | dt	        | j
                         d| dt	        |j
                         d
       | j                  t        u rt        | j                        t        |j                        k7  r* d | d| j                   d| d|j                   	       t        t        |j                  |j
                              }| j                  D cg c]  }||   	 }}n|j
                  }t        t        | j
                  |            D ]2  \  }\  }}	 
||	| | j                  | j                  |      gz          4 y c c}w )	N`z` is a z, but `dynamic_shapesz` is notz` has z elements, but `dynamic_shapesz	 elementsz` has keys )r   r   r   rA   lenchildren_specsr   sortedr   zip	enumerate)r   r   r   rendered_path_remapkdynamic_shapes_children_specsr   tree_dynamic_shapes__comparer   r  r   s             r)   r  z%_tree_map_with_path.<locals>._compare  s#    !'tdH-nh7(I;}oWTYYK H..;_HF 99 3 33(I;}oWTYYK H..;_GNDWDWCXZ t**+s>3P3P/QQ(I;}oVC@S@S<T;U V..;_F3~GdGdCeBffoq 99$dll+vn6L6L/MM,	{=/T\\N S22?NLbLbKce "N22N4Q4QRF IM4U1VAY4U14U4B4Q4Q13<++-JK4 /A/ 'TYYa @AA 5Vs   Hr   N)r   
ValueErrorargsr   )r   r   r   r   e_	tree_spec
other_treeother_tree_specr  r   r   r   r  s   ` `      @@@@@r)   _tree_map_with_pathr    s    262J!!TLNLGLL H" "W#WW>WWW9E)V (g>LAy, 9
%1*g%F"?OR89 	QHs   # 	BA$BBc                 >   t        | t              r| j                         } |szt        | t        j                  j
                        rt        j                  | j                        nt        j                  |       }||ni } |j                  |i |j                  S |S r:   )r   r   moduler   nnModuler~   	signatureforwardbind	arguments)r   r  kwargs_is_torch_jit_tracer  s        r)   _combine_argsr#  I  s     !_%HHJ !UXX__- aii(""1% 	
 "-2y~~t.v.888Kr(   c                   0    e Zd ZdZd Zd Zd Zd ZddZy)	ShapesCollectionaD  
    Builder for dynamic_shapes.
    Used to assign dynamic shape specifications to tensors that appear in inputs.

    This is useful particularly when :func:`args` is a nested input structure, and it's
    easier to index the input tensors, than to replicate the structure of :func:`args` in
    the :func:`dynamic_shapes` specification.

    Example::

        args = ({"x": tensor_x, "others": [tensor_y, tensor_z]})

        dim = torch.export.Dim(...)
        dynamic_shapes = torch.export.ShapesCollection()
        dynamic_shapes[tensor_x] = (dim, dim + 1, 8)
        dynamic_shapes[tensor_y] = {0: dim * 2}
        # This is equivalent to the following (now auto-generated):
        # dynamic_shapes = {"x": (dim, dim + 1, 8), "others": [{0: dim * 2}, None]}

        torch.export(..., args, dynamic_shapes=dynamic_shapes)
    c                     i | _         y r:   )_shapesre   s    r)   __init__zShapesCollection.__init__p  s	    r(   c                    t        |t        j                        sJ dt        |              t	        |      }|| j
                  v r"| j
                  |   }||k(  sJ d| d|        y || j
                  t	        |      <   y )Nz'Cannot assign shape to non-tensor type z1Shapes assigned to tensor do not match: expected z, got )r   r   TensorrA   idr'  )rf   r   shaper   _shapes        r)   __setitem__zShapesCollection.__setitem__s  s    u||
 	?4T!WI>	? 
 !u4<<\\$'FYB6(&QVPWXY #(DLLAr(   c                 p    t        |      }|| j                  vri | j                  |<   | j                  |   S r:   )r+  r'  )rf   r   r   s      r)   __getitem__zShapesCollection.__getitem__  s4    !ut||#!#DLL||D!!r(   c                 ,    t        | j                        S r:   )r  r'  re   s    r)   __len__zShapesCollection.__len__  s    4<<  r(   Nc                      t                fd}t        |||      }t        ||      }t        fd j                  D              rt        d      |S )zu
        Generates the :func:`dynamic_shapes` pytree structure according to :func:`args` and :func:`kwargs`.
        c                 x    t        |      }|j                  v r j                  |       j                  |   S y r:   )r+  r'  r   )r   r   r   rf   t_idss      r)   
find_shapez3ShapesCollection.dynamic_shapes.<locals>.find_shape  s5    a5Dt||#		$||D))r(   c              3   &   K   | ]  }|v 
 y wr:   r'   )r   r   r5  s     r)   r   z2ShapesCollection.dynamic_shapes.<locals>.<genexpr>  s     :Tt5 :r   zSome tensors that were assigned shapes were not found in args. Maybe such tensors were copied when passing them as args? Maybe such tensors are contained in classes that were not registered with pytree?)setr#  r  anyr'  r  )rf   mr  r!  r6  combined_argsr   r5  s   `      @r)   r   zShapesCollection.dynamic_shapes  sZ    
 	 &av6,ZG:T\\::d 
 r(   r:   )	r    r!   r"   r#   r(  r.  r0  r2  r   r'   r(   r)   r%  r%  Y  s     ,("!r(   r%  c                  2    d} t         j                  |        y )NzTUsing None as a dynamic shape dimension is deprecated. Please use Dim.STATIC instead)logwarning)r   s    r)   %_warn_on_None_dynamic_shape_dimensionr?    s    	( 
 KKr(   r;  c                   	
 ddl mm |t        |      dk(  ryt	        |t
        t        f      r t        |      | j                               } i fd		fd
t	        |t        t
        t        f      sJ t	        |t              rt        |j                               }t        | j                               }t        |      t        |      k7  rTd| d| d}t        |       d	k(  r#|d   |vrt	        | |d      t              r|d
z  }n|dz  } j                  |d      
fd}t        || |d       y)z
    Checks the dynamic_shapes specification for correctness,
    using combined args + kwargs as reference for inputs structure.
    r   r   Nc           
         | j                   v r| j                      \  }}| j                  |k7  s| j                  |k7  rst        j	                  | j                   ||      }t        j	                  | j                   | j                  | j                        } j
                  d| d| d|  d      y | j                  | j                  f| j                   <   y )NzFound different definitions z and z! for the same symbolic dimension !)r    rg   rj   r+   r6   r   )r   r4   r5   this_that_r   r   boundss        r)   check_same_boundsz0_check_dynamic_shapes.<locals>.check_same_bounds  s    <<6!-JD$ww$#''T/cllD$?cllCGGSWWE!//25'ug F77:e1>  #2 %(GGSWW#5F3<< r(   c                    t        |t              r|j                         D ]l  \  }}t        |t              r	 |       |t	                ,t        |t
        t        f      rC j                  d| d| dt        |        d| d	d       y t        |t        t        f      r{t        |      D ]l  \  }}t        |t              r	 |       |t	                ,t        |t
        t        f      rC j                  d| d| dt        |        d	| d	d       y |% j                  d
| dt        |        dd      y )Nz%Unexpected dimension mapped to index z in input tensor shape  specified at `dynamic_shapeszP` (expected None, an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC,  but got z	 instead)r   r   zUnexpected dimension #zO` (expected None, an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC, but got zUnexpected input tensor shape z` (expected either a list/tuple of dimensions, or a dict mapping indices to dimensions, where each dimension is an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC))r   r   itemsr+   r?  rB   r   r   r   r   r   r  )r   tensorr,  r   r   r   r   rF  s        r)   check_symbolsz,_check_dynamic_shapes.<locals>.check_symbols  s   eT"++- 3c4(%c*[9;$S3/:#%33?sBYZ_Y` a77=d|n E$$'5	3 #>  t}-#E* 3c4(%c*[9;$S3/:#%3303J5' R77=d|n E##&%y2 #>  ++07TU[\`UaTb c` a 6  r(   zWWhen `dynamic_shapes` is specified as a dict, its top-level keys must be the arg names z  of `inputs`, but here they are z. r   zSince here `inputs` is a list/tuple enclosing a single dict, maybe you just forgot to enclose `dynamic_shapes` in a list/tuple?zwAlternatively, you could also ignore arg names entirely and specify `dynamic_shapes` as a list/tuple matching `inputs`.r   r   c                     t        |t        j                        r | ||       y |6t        |       } j                  d| d| dt        |       d| d	d      y )NzCannot associate shape rH  z` to non-tensor type z at `inputsz` (expected None)r   r   )r   r   r*  r   r   rA   )r   r   dynamic_shaper	  r   r   rK  s       r)   check_shapez*_check_dynamic_shapes.<locals>.check_shape  sx    a&$=1( &t!//-m_<YZgYh i**.q'+m_L]_9	  )r(   inputsr   )r   r   r   r  r   r   r   rA   valuesr   keysr  r   r  )r;  r   got_keysexpected_arg_namesr   rN  r   r   rE  rF  rK  s         @@@@@r)   _check_dynamic_shapesrT    sX    ;^!4!9.5$-0,^,]-A-A-CD)+F6&P ntUD&9:::.$'++-.!-"4"4"67(v&899));(< =!!)
".  M"a'&q)9}-?-BCTJY
 V ++S<W  ]NhWr(   c                   	
 ddl mm |t        |      dk(  rg S t	        |t
        t        f      r t        |      | j                               } t        t              i 
g 	g 	
fdfdfd}t        || |d       	D ]*  }|j                  j                  }|v s|   d   |_        , j                         D ]  }j                  |        S )zT
    Reads the dynamic_shapes specification and produces a list of constraints.
    r   r   c                 0   
 dd l 
ddlm} ddlm ddlm}  
fd}t         t              r/ j                  }|j                  v r3|j                     d   }t        |j                  |j                        }nn|j                  vrQt        |j                   | ||j                  |j                         d       |       	      }||j                  <   n|j                     }t#        t%               j                   | | j                   j                         d      | j&                        }	t        |t              rj)                  |	       |	S t         t*              rGt-        t%               j                   | | j.                   j.                        d            }	|	S t         t0              sJ t-        t%               j                   | | j                   j                         d            }	|	S )
Nr   r   )	try_solver   c                  :   j                  j                  j                  d      } j                  |       } 	j	                  |j
                           |       }|t        |d         S  j                  d dj
                      d| d|  d	      )	NT)integerr   zExpected shape[z] = z# of input Tensor to be of the form z, where z is an integer)r   r]   r    rY   Eqr,  rB   CONSTRAINT_VIOLATION)
symbolexprsolutionr   r   r   r   rW   rJ  rW  s
      r)   
root_valuezB_process_dynamic_shapes.<locals>.to_constraint.<locals>.root_value>  s     \\#(("3"3T\BF66&>D $Q!@&IH#8A;''!66%aSV\\!_,= >##'&H r(   r   Fr   )r3   r   r   )rW   r   r   torch.utils._sympy.solverW  r   r   r   r^   r]   r    r   r   r   r   rg   rj   r   r+  rY   r   ra   r   rd   r+   )r   rJ  r   r   r   r_  dim_rootroot_constraintr]   r   rW   rW  r   r   %derived_constraints_with_phantom_rootphantom_rootssymbolss   ```       @@r)   to_constraintz._process_dynamic_shapes.<locals>.to_constraint7  s   P6?	 	 c;' xxH  G+")(*;*;"<Q"?(#((#'' ""-7#!**%;&X\\N"'& # 48h//0$X%6%67+6
&"@# 
J $- 6<<ZH( ' Z($6
&"#))DPU	J$  c4((($6
&"@E	J r(   c                    d }t               |_        t               |_        t               |_        t               |_        t               |_        t        |t              ri|j                         D ]T  \  }}t        |t        t        f      rCt        |t              r
 ||||      } 	|||      }|j                     j                  |       `t        |t              r|t        j                  k(  r!t        j                   j#                  ||       ng|t        j$                  k(  r!t        j                   j'                  ||       n3|t        j(                  k(  r t        j                   j+                  ||       j                  t-        t/        |      |             1|5t        j                   j'                  ||       W y t        |t0        t2        f      rdt5        |      D ]T  \  }}t        |t        t        f      rCt        |t              r
 ||||      } 	|||      }|j                     j                  |       `t        |t              r|t        j                  k(  r!t        j                   j#                  ||       ng|t        j$                  k(  r!t        j                   j'                  ||       n3|t        j(                  k(  r t        j                   j+                  ||       j                  t-        t/        |      |             1|5t        j                   j'                  ||       W y |?t7        |j9                               D ]"  }t        j                   j'                  ||       $ y y )Nc                 <    t        t        |      t        fd|i      S )Nrd   )ra   rX   rB   )rJ  r   rd   s      r)   _create_static_dimzK_process_dynamic_shapes.<locals>.update_symbols.<locals>._create_static_dim  s    c%j3&7E2BCCr(   )r8  _dynamo_weak_dynamic_indices_dynamo_dynamic_indices_dynamo_dynamic_range_dynamo_static_indices_dynamo_unbacked_indicesr   r   rI  rB   r+   r    r   r   r$   r   r   maybe_mark_dynamicr%   mark_staticr&   mark_dynamicr   r+  r   r   r  ranger   )
r   rJ  r,  ri  r   r   r   constraintsre  rf  s
          r)   update_symbolsz/_process_dynamic_shapes.<locals>.update_symbols  s   	D
 /2e+),&'*u$(+%*-%'eT"++- 93cC;/!#s+0C@!.sFA!>JCLL)00<X.hmm+88C/11&!< 0 002261=&&'9"V*a'HI[MM--fa89  t}-#E* 93cC;/!#s+0C@!.sFA!>JCLL)00<X.hmm+88C/11&!< 0 002261=&&'9"V*a'HI[MM--fa89  ]6::<( 5))&!45 r(   c                 P    t        |t        j                        r | ||       y y r:   )r   r   r*  )r   r   rM  rt  s      r)   assoc_shapez,_process_dynamic_shapes.<locals>.assoc_shape  s"    a&4M2 'r(   rO  r   )r   r   r   r  r   r   r   rA   rP  r   r  r]   r3   r   )r;  r   rv  $derived_constraint_with_phantom_rootphantom_root_namedynamic_dimsr   r   rs  rc  rd  re  rf  rt  s         @@@@@@@@r)   _process_dynamic_shapesrz     s     ;^!4!9	.5$-0,^,]-A-A-CD ,7t+<G-/MFH)$&KQ Qf05d3 ]NhW0U 
V,@EEJJ' 9@@Q8RST8U05
V  ( )<() r(   c                 *   i }t        | d       d   D ]|  }|t        |t              rt        |t              rD|||j                  <   t        |t
              sG|j                  ||j                  j                  <   kt        |t              r|J  |S )Nc                 "    t        | t              S r:   )r   r+   )r<   s    r)   r>   z'_get_dim_name_mapping.<locals>.<lambda>  s    *Q- r(   r  r   )r   r   rB   r+   r    r^   r]   r   )r   name_to_dimr   s      r)   _get_dim_name_mappingr~    s     K- 	 - ;c3T"(+K%#{+14CHH--.c8,,,- r(   r   c           
      $   ddl }ddlddlm}m} ddlm} 	 | j                  d      d   j                         }i |j                  d      D ]  }|j                         }|j                  d	|      x}	r|	j                  d      }
d
\  }}|j                  d|      x}rt        |j                  d            }|j                  d|      x}rt        |j                  d            }t        |
||      |
<   |j                  d      \  }
}j                  |      }t!        |j"                        rt        |      |
<   ||
<    t%        |      t'               }j)                         D ]  \  }}t!        |t        t*        t,        j.                  f      sJ t!        |j.                        rE ||      sJ ||<   |j1                  t3        t5        t7        |j8                                           t!        |t,              s|j1                  |j:                  j<                          j)                         D ]  \  }}|v r||v rJ  i fd}t?        |||      S # t        $ r} ||j                  d      |d}~ww xY w)a  
    When exporting with :func:`dynamic_shapes`, export may fail with a ConstraintViolation error if the specification
    doesn't match the constraints inferred from tracing the model. The error message may provide suggested fixes -
    changes that can be made to :func:`dynamic_shapes` to export successfully.

    Example ConstraintViolation error message::

        Suggested fixes:

            dim = Dim('dim', min=3, max=6)  # this just refines the dim's range
            dim = 4  # this specializes to a constant
            dy = dx + 1  # dy was specified as an independent dim, but is actually tied to dx with this relation

    This is a helper function that takes the ConstraintViolation error message and the original :func:`dynamic_shapes` spec,
    and returns a new :func:`dynamic_shapes` spec that incorporates the suggested fixes.

    Example usage::

        try:
            ep = export(mod, args, dynamic_shapes=dynamic_shapes)
        except torch._dynamo.exc.UserError as exc:
            new_shapes = refine_dynamic_shapes_from_suggested_fixes(
                exc.msg, dynamic_shapes
            )
            ep = export(mod, args, dynamic_shapes=new_shapes)

    r   Nr   )_is_supported_equivalencezSuggested fixes:r   z`Suggested fixes not found in error message given to refine_dynamic_shapes_from_suggested_fixes()
z(.*) = Dim\('(.*)'.*\))NNz!.* = Dim\('.*', min\=([0-9]+).*\)z.* = Dim\('.*'.*max\=([0-9]+)\)ry   z = c                 D   |t        |t              r|S |j                  v r|j                     }t        |j                        rt	        |      	v r	t	        |         S t        t        |j                              }|j                  v r|j                     }n|j                  
v sJ 
|j                     }j                  j                  j                  ||      \  }}|}|dk7  rt        |      |z  }|dk7  r|t        |      z   }|	t	        |      <   |S |S t        |t              rn|j                  j                  v rV|j                  	v r	|j                     S |j                  |j                  j                           }|	|j                  <   |S |S )Nr   r   )r   rB   r    ExprrX   nextiterfree_symbolsr3   polys	polytoolsdivr^   r]   rY   )r   r   dummyfixr\  r]   modulus	remainder_dimderived_dim_cacher}  shape_fixesrW   s            r)   apply_fixesz?refine_dynamic_shapes_from_suggested_fixes.<locals>.apply_fixesC  s   ;*S#.J\\[(cll+C#uzz*s800,SX66!$s'7'7"89F{{k1*6;;7%{{k999*6;;7).)>)>)B)B3)O&GYC!|!'lS0 A~!C	N225%c#h/J
[)chh.?.?;.N||00(66vvk#((*;*;<=26!#,,/
r(   ) rerW   r   r   r   r   r  splitstrip	Exceptionr   matchgrouprB   r   rV   r   Numberr~  r8  rI  r+   r^   r  r   rX   r  r  r  r]   r    r  )r   r   r  r   r   r  shape_fixes_msgexcr  r  r3   r   r   	match_min	match_maxr]  rootsr  cr  r  r}  r  rW   s                       @@@@r)   r   r     sn   @ :O))$67:@@B K$$T* )iikHH6<<5<;;q>D#JD$HH%I3OOyO9??1-.HH%GMMyM9??1-. #Dd =K5)JD$==&D$-$'ID! %)D!%)( (7K eE!!# '1!c4ejjABBBa$,Q///KNIIc$tANN3456a%IIaffoo&' !!# .1K1:--. 13"H {NNKKi  ''n
 	s   "I- -	J6J

J)F)Gdataclassesr~   loggingrt   collectionsr   enumr   r   typingr   r   r   r	   r
   r   torch.utils._pytreer   r   r   r   r   r   r   r   r   exported_programr   rW   r   torch._guardsr   r   r   r   __all__	getLoggerr    r=  r   rA   r+   ra   r^   rX   rB   r   r$   r%   r&   r   r   	dataclassr   r   r   r   r   r   r   r   r8  r   r  r#  r%  r?  rT  rz  r~  r   r'   r(   r)   <module>r     s      
 #  @ @ 
 
 
 . $V g!
t 
BS4 BSJ "@
$ @
F ,0d c 8C= hsm : ==__
 '+	@	@sm	@19#	@
49	@    D
# D
 D
N   " 
* 
 
4 
* 
 
  ; 24FFG
8$8$3*d8n458$ 8$ U38_$%	8$
 u/018$ U8U3E-F#PQR8$ #x-(8$ ]8$~  $	y
38
y
y y }	y
 	yxc3h  H HVpXS>pX$sCx.%*d3iEFpXfqS>q$sCx.%*d3iEFq 
*qh$sCx.%*d3iEF,}L	}L$sCx.%*d3i?@}L 4S>5:tCy01}Lr(   