
    קgb                     X   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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j(        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e0dee1         dee1         fdZ2e+j3        e2_3        e+j4        e2_4        dddde0dee1         dee1         fdZ5e j6         G d d                      Z7e j6         G d de7                      Z8e j6         G d d                       Z9e j6         G d! d"e7                      Z:ee8e:f         Z;d#e;d$ee1e1ged%         f         d&d'dee0ee1e1f         f         d(eed)                  d*eed%ed+         ef                  d,ee0d-f         fd.Z<dd/d0ed1e
f         d2e
d3e
d4ee0         d5e
f
d6Z=dCd5ee0e
f         fd8Z> G d9 d:          Z?d; Z@d<ee0e
f         d3eee0e
f         ee
         ee
         df         fd=ZAd<ee0e
f         d3eee0e
f         ee
         ee
         df         d5eee0e
f         ee
         ee
         df         fd>ZBd<ee0e
f         d3eee0e
f         ee
         ee
         df         d5ee;         fd?ZCd3eee0e
f         ee
         ee
         df         fd@ZDdAe0d3eee0e
f         ee
         ee
         f         d5eee0e
f         ee
         ee
         f         fdBZEdS )D    N)defaultdict)autoEnum)	AnyCallableDictListOptionalSetTuple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dS )_DimHintz
    Enum for dynamic shape hints.
    - AUTO means automatic inference of shape (static or dynamic).
    - STATIC means static shape (always specialized).
    N)__name__
__module____qualname____doc__r   AUTOSTATIC     W/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/export/dynamic_shapes.pyr#   r#   +   s0          466DTVVFFFr+   r#   c                   X    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dS )_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.numbersr1   )namemin_max_r1   s       r,   readablez_Dim.readable;   s    555555199D6>>D<DL#4####</4//////</4//////7t77D777777r+   c                     t                    t          urt          d d| j         d          |                     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>R       QY r+   typeintNotImplementedErrorr$   _deriveclsr@   s    `r,   __add__z_Dim.__add__K   sn    ;;c!!%_E _ _s| _ _ _   {{....///r+   c                     | |z   S r=   r*   rH   s     r,   __radd__z_Dim.__radd__T       U{r+   c                     t                    t          urt          d d| j         d          |                     fd          S )NzAttempted to subtract z from r;   c                     | z
  S r=   r*   r>   s    r,   rA   z_Dim.__sub__.<locals>.<lambda>^   rB   r+   rC   rH   s    `r,   __sub__z_Dim.__sub__W   sn    ;;c!!%_ _ _cl _ _ _   {{....///r+   c                 2    t          d| j         d          )NzAttempted to negate zN. (Only increasing linear operations with integer coefficients are supported.))rF   r$   rH   s     r,   __rsub__z_Dim.__rsub__`   s0    ![3< [ [ [
 
 	
r+   c                     t                    t          usdk    rt          d d| j         d          |                     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,   rA   z_Dim.__mul__.<locals>.<lambda>m   rB   r+   rC   rH   s    `r,   __mul__z_Dim.__mul__f   sv    ;;c!!UaZZ%_ _ _cl _ _ _   {{....///r+   c                     | |z  S r=   r*   rH   s     r,   __rmul__z_Dim.__rmul__o   rM   r+   c                 Z    ddl m} t           | || j                                      S )Nr   )sympify)sympyrY   strr$   )rI   fnrY   s      r,   _derived_namez_Dim._derived_namer   s8    !!!!!!22ggcl++,,---r+   c                 \    t          |                     |          t          f| |d          S )Nrootr\   )_DerivedDimr]   rE   )rI   r\   s     r,   rG   z_Dim._derivew   s,    3,,R003&3b:Q:QRRRr+   N)r$   r%   r&   r'   staticmethodr9   rJ   rL   rP   rR   rU   rW   r]   rG   r*   r+   r,   r.   r.   6   s          8 8 \80 0 0  0 0 0
 
 
0 0 0  . . .
S S S S Sr+   r.   c                   >    e Zd ZdZed             Zed             ZdS )
_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   
    zr+   c                     | j         S r=   rf   rh   s    r,   maxz_StaticDim.max   rk   r+   N)r$   r%   r&   r'   propertyrj   rm   r*   r+   r,   rd   rd   {   sT            X   X  r+   rd   c                   D    e Zd ZdZed             Zed             Zd ZdS )ra   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        }|dk    s#J d| j         d|j         d|j         d            t          |          S )Nr   Integerr0   zExpected derived min value of z9 to be >= 0. Please specify an appropriate min value for  (currently ).)	rZ   rr   r5   r1   r`   rj   r\   r$   rE   )ri   rr   r1   _min_symintr`   s        r,   rj   z_DerivedDim.min   s     	"!!!!!5555559=VG##7Nggggdim4455ya'T] ' ';?=' '(' ' '  
 ;r+   c           
      B   ddl m} ddlm} | j        j        |u r|S |                      || j        j                            }| j        }|t          j        dz
  k    s3J d| j	         dt          j        dz
   d|j	         d|j         d		            t          |          S )
Nr   rq   r0   r   zExpected derived max value of z
 to be <= z.. Please specify an appropriate max value for rs   rt   )rZ   rr   r5   r1   r`   rm   r\   sysmaxsizer$   rE   )ri   rr   r1   _max_symintr`   s        r,   rm   z_DerivedDim.max   s     	"!!!!!5555559=F""Mggggdim4455yckAo---'T] ' 'ckTUo ' ';?=' '(' ' ' .--
 ;r+   c                 r     t                                         t          f j         fdd          S )Nc                 @                          |                     S r=   )r\   )r?   r\   ri   s    r,   rA   z%_DerivedDim._derive.<locals>.<lambda>   s    4771:: r+   r_   )ra   r]   rE   r`   )ri   r\   s   ``r,   rG   z_DerivedDim._derive   sH     r""FY&>&>&>&>&>??
 
 	
r+   N)r$   r%   r&   r'   rn   rj   rm   rG   r*   r+   r,   ra   ra      sc              X &     X &
 
 
 
 
r+   ra   rj   rm   r6   rj   rm   c                V   ddl m} |dn|}||n|}||k    sJ d| d|             |                                 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   r0   Nz(Cannot create Dim with inconsistent min=r4   z)Dim name must be a valid identifier, got r|   r   r$   __main__)
r5   r1   isidentifierr.   rE   getattrinspect	getmodulestackr%   )r6   rj   rm   r1   _min_maxdims          r,   r   r      s      21111111D[66cD$;;;S3SScSS;;;RR RD R RRRR
tcVT$77
8
8C'-//!,Q/00*j CN Jr+   namesc                 >     t           fd|D                       S )z4
    Util to create multiple :func:`Dim` types.
    c              3   <   K   | ]}t          |           V  dS )r|   N)r   ).0r6   rm   rj   s     r,   	<genexpr>zdims.<locals>.<genexpr>   s2      ??Ts,,,??????r+   )tuple)rj   rm   r   s   `` r,   r    r       s,     ???????????r+   c                   (    e Zd ZU dZeed<   eed<   dS )_ConstraintTargetz2
    This represents input tensor dimensions.
    t_idr   N)r$   r%   r&   r'   rE   __annotations__r*   r+   r,   r   r      s.           III	HHHHHr+   r   c                   d    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dS )_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.
    r6   r   constraint_ranger   Nc                     ddl m} ddlm} ddlm} ||} || j        j         |||          z  d          }t          | j	        | j
        | j        |          S )Nr   r   r0   ValueRangeslowerupperFvr	warn_only)%torch.fx.experimental.symbolic_shapesr   r5   r1   torch.utils._sympy.value_rangesr   r   r   r   r   r   r6   )ri   r   r   r   r1   r   r   s          r,   _clone_with_rangez_Constraint._clone_with_range  s    PPPPPP555555??????=E11$'++E*O*O*OO
 
 
 IHI	
 
 	
r+   c                 .    |                      |          S )Nr   r   ri   r   s     r,   __ge__z_Constraint.__ge__!      %%E%222r+   c                 4    |                      |dz             S )Nr   r   r   r   s     r,   __gt__z_Constraint.__gt__$      %%EAI%666r+   c                 .    |                      |          S )Nr   r   ri   r   s     r,   __le__z_Constraint.__le__'  r   r+   c                 4    |                      |dz
            S )Nr   r   r   r   s     r,   __lt__z_Constraint.__lt__*  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.)	TypeErrorrh   s    r,   __bool__z_Constraint.__bool__-  s    
 7
 
 	
r+   c                 `    | j         | j        | j        j        j        | j        j        j        dS N)r   r   rj   rm   r   r   r   r   r   r   rh   s    r,   serializable_specz_Constraint.serializable_spec8  s5     I8(+1(+1	
 
 	
r+   )r   N)r$   r%   r&   r'   r[   r   r   r   r   r   r   r   rn   r   r*   r+   r,   r   r     s           III....
 
 
 
(3 3 37 7 73 3 37 7 7	
 	
 	
 
 
 X
 
 
r+   r   c                   2    e Zd ZU dZeed<   ded<   eed<   dS )_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.
    r6   r   r   valN)r$   r%   r&   r'   r[   r   rE   r*   r+   r,   r   r   I  s:         	 	 III....	HHHHHr+   r   c                   b    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dS )	_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.
    r6   r   r   r`   r\   c                 `    | j         | j        | j        j        j        | j        j        j        dS r   r   rh   s    r,   r   z$_DerivedConstraint.serializable_speck  s5     I8(+1(+1	
 
 	
r+   N)r$   r%   r&   r'   r[   r   r   r   r   r   rn   r   r*   r+   r,   r   r   [  sp           III....
!</
0000LLL
 
 X
 
 
r+   r   
constraintget_sourcesr   	shape_envr   source_pairs)r   r   derived_equalities)r   r   phantom_symbolsr   c                 ~    || j         | j                  }|sdS |^}|                    fd|D                        t          | t                    s`| j        |v r?|| j                 \  }	}
 ||	|
          }|                    fd|D                        dS | j         | j        f|| j        <   dS t          | j        t                    s' || j        j         | j        j                  d         }n| j        j        |v r|| j        j                 }n|                    | j        j	        t          j        j                            | j        j                  t          j        j        j        j        j        | j        j                  }||| j        j        <   | j        }|                    ||f           dS )z
    Updates `source_pairs`, `derived_equalities`, and `phantom_symbols` (which become
    fields of `EqualityConstraint`) based on a given input `constraint`.
    Nc              3       K   | ]}|fV  	d S r=   r*   r   other_sourcesources     r,   r   z&_process_equalities.<locals>.<genexpr>  s(      QQ<.QQQQQQr+   c              3       K   | ]}|fV  	d S r=   r*   r   s     r,   r   z&_process_equalities.<locals>.<genexpr>  s9          +7&           r+   r   )r   r   dynamic_dimconstraint_dim)r   r   extend
isinstancer   r6   r`   r   create_symbolr   torch_dynamor   ConstantSourcefxexperimentalsymbolic_shapes
DimDynamicDYNAMICr   r\   append)r   r   r   r   r   r   r   sourcesother_sourcesshared_t_id
shared_dimr`   r\   r   s                @r,   _process_equalitiesr   y  s    k*/:>::G $F] QQQQ=QQQQQQj"455 6?e##&+JO&<#K'KZ@@M        ;H           '1oz~%FE*/""" */<88 	=;z3Z_5HII!LDD #66&z';< !.."+ =/>>z?STT % 5 E P X#-?#C	 /   9=
 45] 	!!64"455555r+   	tree_namefunc.treedynamic_shapesr   returnc                N   	
 d  fd	 t          |g|R diS # t          $ rv}d|j        d         v ra|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 r5t          t          |                             |          d         g|R diS  | |g|R  S )Nr   r   )r   r   r   
flatten_fn)pathr   r   typfr   r   s       r,   r   z_tree_map_with_path.<locals>.f  s    Q/!! &$//2215      	   4a1.1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  sX    D==%gaj111T5M))"???&q>>)$%CE%C%CDDDr+   c                 F    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  sQ    FFFFFFFFi!/k9kkfikk9   r+   c                    t          |          }t          | t                    rd S t          |t                    r d | d| j         d| d           | j        |j        k    r# d | d| j         d| d|j         	           t	          | j                  t	          |j                  k    r> d | dt	          | j                   d| dt	          |j                   d
           | j        t          u rt          | j                  t          |j                  k    r# d | d| j         d| d|j         	           t          t          |j        |j                            fd	| j        D             }n|j        }t          t          | j        |                    D ].\  }\  }} 	||| 
| j        | j        |          gz              /d S )
N`z` is a z, but `dynamic_shapesz` is notz` has z elements, but `dynamic_shapesz	 elementsz` has keys c                      g | ]
}|         S r*   r*   )r   k_remaps     r,   
<listcomp>z9_tree_map_with_path.<locals>._compare.<locals>.<listcomp>  s    4U4U4U1VAY4U4U4Ur+   )r   r   r   rD   lenchildren_specsr   sortedr   zip	enumerate)r   r   r   rendered_pathdynamic_shapes_children_specsr   tree_dynamic_shapes_r  _comparer   r   r   s           @r,   r  z%_tree_map_with_path.<locals>._compare  s    !'tdH-- Fnh77 ((FI F} F FTY F F.;F F F   9 333((ZI Z} Z ZTY Z Z.;Z ZDRDWZ Z   t*++s>3P/Q/QQQ((qI q} q qC@S<T<T q q.;q qCF~GdCeCeq q q   9$$dl++vn6L/M/MMM,,e	 e= e eT\ e e2?e eLZLbe e   "N2N4QRR F 5V4U4U4U4U4U4U114B4Q13<+-JKK4 4  /A/ H'TYa @ @AA    r+   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    sk   26 6 62 2 2 2 2 2 2J!!TLNLLLGLLL H H H"" "WW#WWWWWWWWWWE E E    ) ) ) ) ) ) ) )V (g>>>LAy, 9 9
%1*g%F%F"?OR8888QHs   $ 
B$A1BB$Fc                 $   t          | t                    r|                                 } |sdt          | 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"  -  s     !_%% HHJJ 9 !UX_--&Gai((("1%% 	
 "-2y~t.v..88Kr+   c                   2    e Zd ZdZd Zd Zd Zd ZddZdS )	ShapesCollectionab  
    Builder for dynamic_shapes.
    Used to assign dynamic shape specifications to tensors that appear in inputs.

    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 | _         d S r=   )_shapesrh   s    r,   __init__zShapesCollection.__init__O  s    r+   c                    t          |t          j                  sJ dt          |                       t	          |          }|| j        v r%| j        |         }||k    sJ d| d|             d S || j        t	          |          <   d S )Nz'Cannot assign shape to non-tensor type z1Shapes assigned to tensor do not match: expected z, got )r   r   TensorrD   idr&  )ri   r   shaper   _shapes        r,   __setitem__zShapesCollection.__setitem__R  s    u|
 
 	? 	?>T!WW>>	? 	? 	? !uu4<\$'FX6XXQVXX   #(DLAr+   c                 P    t          |          }|| j        v r| j        |         S d S r=   )r*  r&  )ri   r   r   s      r,   __getitem__zShapesCollection.__getitem__`  s,    !uu4<<%%4r+   c                 *    t          | j                  S r=   )r  r&  rh   s    r,   __len__zShapesCollection.__len__g  s    4<   r+   Nc                      t                       fd}t          |||          }t          ||          }t          fd j        D                       rt          d          |S )z*
        Generate dynamic_shapes.
        c                 |    t          |          }|j        v r"                    |           j        |         S d S r=   )r*  r&  add)r   r   r   ri   t_idss      r,   
find_shapez3ShapesCollection.dynamic_shapes.<locals>.find_shapeq  s<    a55Dt|##		$|D))tr+   c              3       K   | ]}|vV  	d S 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  )ri   mr  r   r6  combined_argsr   r5  s   `      @r,   r   zShapesCollection.dynamic_shapesj  s    
 	 	 	 	 	 	 &av66,ZGG::::T\::::: 	d  
 r+   r=   )	r$   r%   r&   r'   r'  r-  r/  r1  r   r*   r+   r,   r$  r$  =  sn         "  ( ( (  ! ! !     r+   r$  c                  >    d} t                               |            d S )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 ddlm} |t          |          dk    rdS t          |t          t          f          r* t          |          | 
                                          } i 
fd
fdt          |t          t          t          f          sJ t          |t                    rt          |                                          }t          |                                           }t          |          t          |          k    red| d| d	}t          |           d
k    r1|d         |vr't          | |d                  t                    r|dz  }n|dz  } 
j        |d          
fd}t          || |d            || |          }t!          |          \  }}	t#          d |D                       r,t#          d |D                       r 
j        dd          dS dS )z
    Checks the dynamic_shapes specification for correctness,
    using combined args + kwargs as reference for inputs structure.
    r   r   )_flatten_dynamic_shapesNc           
      d   | j         v r| j                  \  }}| j        |k    s| j        |k    rgt                              | j         ||          }t                              | j         | j        | j                  } j        d| d| d|  d          d S | j        | j        f| j         <   d S )NzFound different definitions z and z! for the same symbolic dimension !)r$   rj   rm   r.   r9   r   )r   r7   r8   this_that_r   r   boundss        r,   check_same_boundsz0_check_dynamic_shapes.<locals>.check_same_bounds  s    <6!!-JD$w$#'T//clD$??clCGSWEEi!/>5 > >u > >7:> > >   #2/ %(GSW#5F3<   r+   c                    t          |t                    r|                                D ]\  }}t          |t                    r |           &|t	                       7t          |t
          t          f          s- j        d| d| dt          |            d| d	d          d S t          |t          t          f          rt          |          D ]\  }}t          |t                    r |           &|t	                       7t          |t
          t          f          s- j        d| d| dt          |            d| d	d          d S |' j        d	| dt          |            d
d          d S )Nz%Unexpected dimension mapped to index z in input tensor shape  specified at `dynamic_shapeszB` (expected None, an int, a Dim, Dim.AUTO, or Dim.STATIC, but got z	 instead)r   r   zUnexpected dimension #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, or Dim.STATIC))r   r   itemsr.   r?  rE   r#   r   r   r   r   r	  )r   tensorr+  r   r   r   r   rG  s        r,   check_symbolsz,_check_dynamic_shapes.<locals>.check_symbols  sh   eT"" #	++--  3c4(( %%c****[9;;;;$S3/:: #)%3j j jZ_ j j7=d||j j[^j j j #>     t}-- 	#E**  3c4(( %%c****[9;;;;$S3/:: #)%3j j j5 j j7=d||j j[^j j j #>     )+T T TU[\`UaUa T T T 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 | ||           d S |<t          |           } j        d| d| dt          |           d| d	d          d S )NzCannot associate shape rI  z` to non-tensor type z at `inputsz` (expected None)r   r   )r   r   r)  r   r   rD   )r   r   dynamic_shaper
  r   r   rL  s       r,   check_shapez*_check_dynamic_shapes.<locals>.check_shape  s    a&& 
	M$=11111( &ti!/_m _ _Zg _ _*.q''_ _>K_ _ _9	    )(r+   inputsr   c              3   @   K   | ]}t          |t                    V  d S r=   r   r.   r   ss     r,   r   z(_check_dynamic_shapes.<locals>.<genexpr>  s,      
?
?1:a
?
?
?
?
?
?r+   c              3   6   K   | ]}|t           j        k    V  d S r=   )r#   r(   rS  s     r,   r   z(_check_dynamic_shapes.<locals>.<genexpr>  sB       H H X]H H H H H Hr+   aw  Specifying both `Dim.AUTO` and `Dim` or `DerivedDim` in `dynamic_shapes` is not well supported at the moment, and can easily lead to constraint violation errors or obscure errors in torch.export. Dim/DerivedDims expect all equal or related dimensions to be specified, and does not yet compose well with `Dim.AUTO`. We suggest using `Dim.AUTO` mixed with `None` for auto-dynamic + static shapes, plus torch._check(dim >= min), torch._check(dim <= max) calls in your program to specify min/max ranges, or `Dim`/`DerivedDim` mixed with `None` if you want to assert on the exact specification of your program's dynamic shapes behavior.)r   r   r   torch._export.non_strict_utilsrA  r  r   r   r   rD   valuesr   keysr  r   r  r   r9  )r;  r   rA  got_keysexpected_arg_namesr   rO  flat_dynamic_shapesflatter_dynamic_shapesr  r   r   rF  rG  rL  s             @@@@@r,   _check_dynamic_shapesr]    s    ;:::::::FFFFFF^!4!4!9!9.5$-00 E,^,,]-A-A-C-CDD)+F6 6 6 6 6 6 6$ $ $ $ $ $ $L ntUD&9:::::.$'' ++--..!-"4"4"6"677(v&89999.);. .!). . .  M""a''&q)99}-?-BCTJJ : Y
 V )+S<W          ]NhWWWW 21-PP ,-@ A AA

?
?(>
?
?
??? 
C H H$:H H H E E 
 i'j 2	
 	
 	
 		

 
 
 
r+   c                    fd|t          |          dk    r | d          }t          |t          t          f          r* t	          |          |                                           } d fd}t          || |d          }|S )a  
    In the long run this might not be needed, but this exists because export.export() and _dynamo.export()
    historically have different semantics for how dynamic_shapes are specified, but go through the same
    process of producing constraints, and now both use assume_static_by_default=False.

    For _dynamo.export(), the semantics for dynamic_shapes are:
    - None: dynamic, allocated a symbol
    - Dim/DerivedDim: a strict assertion on the min/max range for this symbol, and require a specification
      for all dims governed by this symbol (i.e. relations, equality, linear relations, etc.)

    For export.export(), historically dynamism for unspecified dims has been undesirable, so the semantics are:
    - Dim.AUTO: dynamic, allocated a symbol
    - None/unspecified/Dim.STATIC: static
    - Dim/DerivedDims: also a strict assertion

    To allow both APIs to follow the same process for producing constraints, this function converts dynamic_shapes
    for export.export() to be compatible with _process_dynamic_shapes() and assume_static_by_default=False, turning them
    into essentially what they'd look like for _dynamo.export().

    An example conversion might look like, for a 3-d input tensor:

        input spec: {
            0: Dim.AUTO,
            1: None,  # or Dim.STATIC
            2: Dim("dx"),
        }
        output spec: {
            0: None,  # None: dynamic by default
            1: 32,  # explicitly provide static shape
            2: Dim("dx"),  # remains the same
        }
    c                     t          |           x}t          vrS t          |         j        } ||           \  }}t          |t          v r|nt                   j        }fd|D             } |||          S )a  
        If the user generally specifies dynamic_shapes=None for a pytree input,
        we'd like to convert this into a tree of Nones following the input spec,
        so we can explicitly specify static dims for all tensor dimensions.
        Non-builtin types for pytree (e.g. custom dataclasses) creates some difficulty,
        in which case the correct format is a list containing specs for each child attribute.
        c                 (    g | ]} |          S r*   r*   )r   child_tree_map_helperr   s     r,   r  zS_transform_shapes_for_default_dynamic.<locals>._tree_map_helper.<locals>.<listcomp>D  s'    LLLU$$UC00LLLr+   )r   r   r   r   r   unflatten_fn)	r   r   	node_typer   child_pytreesr   rc  childrenrb  s	    `      r,   rb  z?_transform_shapes_for_default_dynamic.<locals>._tree_map_helper5  s     (---IoEEJ$Y/:
!+D!1!1w&"m33II

 	 MLLLLmLLL|g
 
 	
r+   Nr   c                    d }d }t          |t                    ri }t          |j                  D ]\  }}|                    |t
          j                  } |||          s|t
          j        k    r1|t
          j        k    r t          j	        
                    ||           rt          |t                    r|||<   t          |t                    r|||<   |t                       |||<   |t
          j        k    sJ |||<   ֐nt          |t          t          f          rDg }t          |j                  D ]\  }}||         } |||          s|t
          j        k    rF|t
          j        k    r t          j	        
                    ||           |                    d            pt          |t                    r|                    |           t          |t                    r|                    |           |$t                       |                    |           |t
          j        k    sJ |                    |            t#          |          |          }nd|J t          |t          j                  rDg }t          |j                  D ](\  }}|                     |||          rd n|           )|pd }nd }|S )Nc                 @    |t          | dt                                v S )N_dynamo_dynamic_indices)r   r8  )rK  r   s     r,   _marked_dynamiczX_transform_shapes_for_default_dynamic.<locals>.transform_shapes.<locals>._marked_dynamicQ  s    (A355IIIIr+   )r   r   r	  r+  getr#   r)   r(   r   r   maybe_mark_dynamicr.   rE   r?  r   r   r   rD   r)  )r   rK  r+  rj  outr   r   r   s           r,   transform_shapesz?_transform_shapes_for_default_dynamic.<locals>.transform_shapesP  s   	J 	J 	J 7;eT"" 2	C#FL11 ! !3ii8?33"?61-- !1E1E hm++88CCCT** ! CFFS)) 
! !CFF[9;;; CFF (/1111 CFF)!* t}-- 	C#FL11 $ $3Ah"?61-- $1E1Ehm++88CCCJJt$$$$T** 	$JJsOOOOS)) $JJsOOOO[9;;;JJsOOOO(/1111JJsOOOO$u++c""CC===&%,// '55 L LFAsJJvq'A'AJttsKKKKkT
r+   c                 V    t          |t          j                  r | ||          S d S r=   r   r   r)  )r   r   rN  rn  s      r,   transform_shapez>_transform_shapes_for_default_dynamic.<locals>.transform_shape  s6    a&& 	<##D!];;;	< 	<r+   rP  r   )r  r   r   r   rD   rW  r  )r;  r   rq  resultrb  rn  s       @@r,   %_transform_shapes_for_default_dynamicrs    s    J
 
 
 
 
* 	#n"5"5":":))->>.5$-00 E,^,,]-A-A-C-CDD9 9 9v< < < < < !(  F Mr+   c                   	
 ddl mm |t          |          dk    rg S t	          |t
          t          f          r* t          |          |                                           } t          t                    i 
g 		
fdfdfd}t          || |d           g }	D ]%}|j        j        }|v r|         d         |_        &                                D ]}|                    |           |S )	zT
    Reads the dynamic_shapes specification and produces a list of constraints.
    r   r   Nc                    
 dd l 
ddlm} ddlm ddlm}  
fd}t           t                    r j	        }|j
        v r.|j
                 d         }t          |j        |j                  }n`|j
        vrJt          |j
         | ||j        |j                  d           |            	          }||j
        <   n|j
                 }t#          t%                     j
         | | j         j                  d          | j                  }	t          |t                    r                    |	           nt           t*                    rEt-          t%                     j
         | | j         j                  d                    }	nDt-          t%                     j
         | | j         j                  d                    }	|	S )
Nr   r   )	try_solver   c                  F                        j        j        d          }                     |           } 	                    |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$   r\   Eqr+  rE   CONSTRAINT_VIOLATION)
symbolexprsolutionr   r   r   r   rZ   rK  rv  s
      r,   
root_valuezB_process_dynamic_shapes.<locals>.to_constraint.<locals>.root_value  s     \\#("3T\BBF66&>>D y$Q!@!@&IIH#8A;'''i!6Ha H HV\!_ H H#'H H17H H H  r+   r   Fr   )r6   r   r   )rZ   r   r   torch.utils._sympy.solverv  r   r   r   ra   r`   r$   r   r   r   r   rj   rm   r   r*  r\   r   rd   r   rg   )r   rK  r   r   r   r~  dim_rootroot_constraintr`   r   rZ   rv  r   r   %derived_constraints_with_phantom_rootphantom_rootssymbolss   ```       @@r,   to_constraintz._process_dynamic_shapes.<locals>.to_constraint  s   PPPPPP666666??????	 	 	 	 	 	 	 	 	 	 	 c;'' 9	 xH G++")(*;"<Q"?(#(#'  "-77#!*%;%;&;X\NNN"'& & & #
   48h/00$X%67+6

&&"{@@@#   
 
J $-- I 6<<ZHHHZ(( 	$6

&&"{#)DDDPU  	 JJ %6

&&"{@@@E  	 J r+   c                    d }t          |t                    r|                                D ]p\  }}t          |t          t          f          rOt          |t                    r ||||          } |||          }|j                                     |           qd S t          |t          t          f          rt          |          D ]r\  }}t          |t          t          f          rOt          |t                    r ||||          } |||          }|j                                     |           qd S d S )Nc                 N    t          t          |          t          fd|i          S )Nrg   )rd   r[   rE   )rK  r   rg   s      r,   _create_static_dimzK_process_dynamic_shapes.<locals>.update_symbols.<locals>._create_static_dim  s!    c%jj3&7E2BCCCr+   )
r   r   rJ  rE   r.   r$   r   r   r   r	  )	r   rK  r+  r  r   r   r   r  r  s	          r,   update_symbolsz/_process_dynamic_shapes.<locals>.update_symbols  sm   	D 	D 	D eT"" 	=++-- = =3cC;// =!#s++ A00C@@!.sFA!>!>JCL)00<<<= = t}-- 	=#E** = =3cC;// =!#s++ A00C@@!.sFA!>!>JCL)00<<<	= 	== =r+   c                 Z    t          |t          j                  r | ||           d S d S r=   rp  )r   r   rN  r  s      r,   assoc_shapez,_process_dynamic_shapes.<locals>.assoc_shape  s;    a&& 	3N4M22222	3 	3r+   rP  r   )r   r   r   r  r   r   r   rD   rW  r   r  r`   r6   r   )r;  r   r  constraints$derived_constraint_with_phantom_rootphantom_root_namedynamic_dimsr   r   r  r  r  r  r  s          @@@@@@@r,   _process_dynamic_shapesr    s    ;:::::::^!4!4!9!9	.5$-00 E,^,,]-A-A-C-CDD ,7t+<+<G-/MFH)P P P P P P P P Pd= = = = = =&3 3 3 3 3 ]NhWWWWK0U 
V 
V,@EJ'' 9@@Q8RST8U05(( ) )<((((r+   c                    i }t          | d           d         D ]e}|t          |t                    rt          |t                    sJ |||j        <   t          |t
                    r|j        ||j        j        <   f|S )Nc                 ,    t          | t                    S r=   rR  )r?   s    r,   rA   z'_get_dim_name_mapping.<locals>.<lambda>.  s    *Q-- r+   r  r   )r   r   rE   r.   r$   ra   r`   )r   name_to_dimr   s      r,   _get_dim_name_mappingr  (  s     K--   	 6 6 ;c3 	#t$$$$$$'CL!c;'' 	6-0XK)*r+   r   c           
         ddl }ddlddlm}m} ddlm} 	 |                     d          d                                         }n$# t          $ r} ||j
        d          |d}~ww xY wi |                    d          D ].}|                                }|                    d	|          x}	r|	                    d          }
d
\  }}|                    d|          x}r"t          |                    d                    }|                    d|          x}r"t          |                    d                    }t          |
||          |
<   |                    d          \  }
}                    |          }t!          |j                  rt          |          |
<   )||
<   0t%          |          t'                      }                                D ]\  }}t!          |t          t*          t,          j        f          sJ t!          |j                  rS ||          sJ ||<   |                    t3          t5          t7          |j                                                 t!          |t,                    r|                    |j        j                   ̉                                D ]\  }}|v s||v sJ i fd}t?          |||          S )aU  
    For working with export's dynamic shapes suggested fixes, and/or automatic dynamic shapes.
    Refines the given dynamic shapes spec, given a ConstraintViolation error message and the original dynamic shapes.

    For most cases behavior is straightforward - i.e. for suggested fixes that specialize or refine a Dim's range,
    or fixes that suggest a derived relation, the new dynamic shapes spec will be updated as such.

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

    However, suggested fixes associated with derived dims can be more complicated.
    For example, if a suggested fix is provided for a root dim, the new derived dim value is evaluated based on the root.

    e.g.
    dx = Dim('dx')
    dy = dx + 2
    dynamic_shapes = {"x": (dx,), "y": (dy,)}

    Suggested fixes:

        dx = 4  # specialization will lead to dy also specializing = 6
        dx = Dim('dx', max=6)  # dy now has max = 8

    Derived dims suggested fixes can also be used to express divisibility constraints.
    This involves creating new root dims that aren't tied to a particular input shape.
    In this case the root dims won't appear directly in the new spec, but as a root of
    one of the dims.

    e.g.
    Suggested fixes:

        _dx = Dim('_dx', max=1024)  # this won't appear in the return result, but dx will
        dx = 4*_dx  # dx is now divisible by 4, with a max value of 4096
    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]+)\)r|   z = c                 (   |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
                            ||          \  }}|}|dk    rt          |          |z  }|dk    r|t          |          z   }|	t	          |          <   |S |S t          |t                    rU|j        j        v rG|j        	v r	|j                 S |                    |j        j                           }|	|j        <   |S |S )Nr   r   )r   rE   r$   Exprr[   nextiterfree_symbolsr6   polys	polytoolsdivra   r`   r\   )r   r   dummyfixr{  r`   modulus	remainder_dimderived_dim_cacher  shape_fixesrZ   s            r,   apply_fixesz?refine_dynamic_shapes_from_suggested_fixes.<locals>.apply_fixes  s   ;*S#..;J\[((cl+C#uz** s88000,SXX66!$s'7"8"899F{k11*6;7%{k9999*6;7).)>)B)B3)O)O&GYC!||!'llS0 A~~!C	NN225%c#hh/J
[)) 	ch.?;.N.N|000(66vvk#(*;<==26!#,/
r+   ) rerZ   r   r   r   r   r  splitstrip	Exceptionr   matchgrouprE   r   rY   r   Numberr  r8  rJ  r.   ra   r  r4  r[   r  r  r  r`   r$   r  )r   r   r  r   r   r  shape_fixes_msgexcr  r  r6   r   r   	match_min	match_maxr|  rootsr  cr  r  r  r  rZ   s                       @@@@r,   r!   r!   <  sV   V IIILLL::::::::OOOOOO))$677:@@BB   i'n
 
 	 K$$T** ) )iikkHH6<<<5 	);;q>>D#JD$HH%I3OOOy /9??1--..HH%GMMMy /9??1--.. #Dd = = =K5))JD$==&&D$-- )$'IID!! %)D!!'77K eeE!!## ' '1!c4ejABBBBBa$$ 	7,,Q/////KNIIc$tAN334455666a%% 	'IIafo&&& !!## . .1K1:::: 13" " " " " " " "H {NNKKKs   -A
 

A+A&&A+)F)Fdataclassesr   loggingrw   collectionsr   enumr   r   typingr   r   r   r	   r
   r   r   r   r   r   torch.utils._pytreer   r   r   r   r   r   r   r   r   exported_programr   rZ   r   torch._guardsr   r   r   r   __all__	getLoggerr$   r=  r#   rD   r.   rd   ra   r[   rE   r   r(   r)   r    	dataclassr   r   r   r   r   r   r  r"  r$  r?  r]  rs  r  r  r!   r*   r+   r,   <module>r     sS         



 # # # # # #         X X X X X X X X X X X X X X X X X X X X X X 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 . - - - - -  W$$$$$$VVVVVVVV   g!!    t   BS BS BS BS BS4 BS BS BSJ       "@
 @
 @
 @
 @
$ @
 @
 @
F ,0d   c 8C= hsm    : =_
 ,0d @ @ @ @8C= @hsm @ @ @ @         D
 D
 D
 D
 D
# D
 D
 D
N        " 
 
 
 
 
* 
 
 
4 ; 223
56563*d8n4556 56 U38_$%	56
 u/0156 U8U3E-F#PQR56 #x-(56 56 56 56x  $	y y y
38
y
y y }	y
 	y y y yx c3h     D D D D D D D DN  @
S>@
$sCx.%*d3iEF@
 @
 @
 @
FBS>B$sCx.%*d3iEFB 4S>5:tCy$67B B B BJPS>P$sCx.%*d3iEFP 
*P P P Pf$sCx.%*d3iEF   (HL	HL$sCx.%*d3i?@HL 4S>5:tCy01HL HL HL HL HL HLr+   