o
    Zh*                     @   s  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rbd dlmZ d d	lmZ d d
l m!Z!m"Z" g dZ#e$e%Z&G dd deZ'G dd de(Z)G dd de)Z*G dd de)Z+dddde,dee- dee- fddZ.e'j/e._/e'j0e._0e'j1e._1dddde,dee- dee- de2e)df fddZ3e j4G dd  d Z5e j4G d!d" d"e5Z6e j4G d#d$ d$Z7e j4G d%d& d&e5Z8e j4G d'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/  d0e;e2d+ed1 ef  d2e<e,d3f d4e=d+ fd5d6Z>dd7d8ede
f d9e
d:e
d;ee, de
f
d<d=Z?dOde<e,e
f fd?d@Z@G dAdB dBZAdCdD ZBdEe<e,e
f d:ee<e,e
f e2e
 e;e
 df fdFdGZCdEe<e,e
f d:ee<e,e
f e2e
 e;e
 df de;e: fdHdIZDd:ee<e,e
f e2e
 e;e
 df fdJdKZEdLe,d:ee<e,e
f e2e
 e;e
 f dee<e,e
f e2e
 e;e
 f fdMdNZFdS )P    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                   @   s"   e Zd ZdZe 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).
    - DYNAMIC means dynamic, will error out if specialized.
    N)__name__
__module____qualname____doc__r   AUTOSTATICDYNAMIC r%   r%   J/var/www/auris/lib/python3.10/site-packages/torch/export/dynamic_shapes.pyr   +   s
    
r   c                   @   s\   e Zd ZdZedd Zdd Zdd Zdd	 Zd
d Z	dd Z
dd Zdd Zdd ZdS )_Dimz*
    Metaclass for :func:`Dim` types.
    c                 C   s   ddl m} |dkrd }||krd }|d u r |d u r d|  dS |d u r-d|  d| dS |d u r: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)   r%   r%   r&   readable=   s   z_Dim.readablec                    6   t  turtd  d| j d|  fddS )NzAttempted to add z to m, where an integer was expected. (Only increasing linear operations with integer coefficients are supported.)c                    s   |   S Nr%   xotherr%   r&   <lambda>T       z_Dim.__add__.<locals>.<lambda>typeintNotImplementedErrorr   _deriveclsr8   r%   r7   r&   __add__M   
   z_Dim.__add__c                 C   s   | | S r4   r%   r@   r%   r%   r&   __radd__V      z_Dim.__radd__c                    r2   )NzAttempted to subtract z from r3   c                    s   |   S r4   r%   r5   r7   r%   r&   r9   `   r:   z_Dim.__sub__.<locals>.<lambda>r;   r@   r%   r7   r&   __sub__Y   rC   z_Dim.__sub__c                 C   s   t d| j d)NzAttempted to negate zN. (Only increasing linear operations with integer coefficients are supported.))r>   r   r@   r%   r%   r&   __rsub__b   s   z_Dim.__rsub__c                    s>   t  tus
 dkrtd  d| j d|  fd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                    s   |   S r4   r%   r5   r7   r%   r&   r9   o   r:   z_Dim.__mul__.<locals>.<lambda>r;   r@   r%   r7   r&   __mul__h   s
   z_Dim.__mul__c                 C   s   | | S r4   r%   r@   r%   r%   r&   __rmul__q   rE   z_Dim.__rmul__c                 C   s   ddl m} t||| jS )Nr   )sympify)sympyrJ   strr   )rA   fnrJ   r%   r%   r&   _derived_namet   s   z_Dim._derived_namec                 C   s   t | |tf| |dS )NrootrM   )_DerivedDimrN   r=   )rA   rM   r%   r%   r&   r?   y   s   z_Dim._deriveN)r   r   r    r!   staticmethodr1   rB   rD   rF   rG   rH   rI   rN   r?   r%   r%   r%   r&   r'   8   s    
			r'   c                   @   s(   e Zd ZdZedd Zed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                 C      | j S r4   valueselfr%   r%   r&   min      z_StaticDim.minc                 C   rT   r4   rU   rW   r%   r%   r&   max   rZ   z_StaticDim.maxN)r   r   r    r!   propertyrY   r[   r%   r%   r%   r&   rS   }   s    
rS   c                   @   s0   e Zd ZdZedd Zedd Zdd ZdS )	rQ   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                 C   sv   ddl m} ddlm} | jj| u r| S | || jj}| j}|dks7J 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 ).)	rK   r^   r-   r)   rP   rY   rM   r   r=   )rX   r^   r)   Z_min_symintrP   r%   r%   r&   rY      s   

z_DerivedDim.minc              
   C   s   ddl m} ddlm} | jj|u r|S | || jj}| j}|tjd ks>J d| j	 dtjd  d|j	 d|j d		t
|S )
Nr   r]   r(   r   zExpected derived max value of z
 to be <= z.. Please specify an appropriate max value for r_   r`   )rK   r^   r-   r)   rP   r[   rM   sysmaxsizer   r=   )rX   r^   r)   Z_max_symintrP   r%   r%   r&   r[      s   z_DerivedDim.maxc                    s&   t  tfj fdddS )Nc                    s     | S r4   )rM   r5   rM   rX   r%   r&   r9      s    z%_DerivedDim._derive.<locals>.<lambda>rO   )rQ   rN   r=   rP   )rX   rM   r%   rc   r&   r?      s
   z_DerivedDim._deriveN)r   r   r    r!   r\   rY   r[   r?   r%   r%   r%   r&   rQ      s    

rQ   rY   r[   r.   rY   r[   c                C   s   ddl m} |du rdn|}|du r|n|}||ks$J d| d| |  s/J d|  t| tf||d}ttt 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(   Nz(Cannot create Dim with inconsistent min=r,   z)Dim name must be a valid identifier, got rd   r   r   __main__)
r-   r)   isidentifierr'   r=   getattrinspect	getmodulestackr   )r.   rY   r[   r)   _min_maxdimr%   r%   r&   r      s   r   namesreturn.c                    s   t  fdd|D S )zh
    Util to create multiple :func:`Dim` types.

    Returns:
        A tuple of :func:`Dim` types.
    c                 3   s    | ]
}t | d V  qdS )rd   N)r   ).0r.   r[   rY   r%   r&   	<genexpr>   s    zdims.<locals>.<genexpr>)tuple)rY   r[   rn   r%   rq   r&   r      s   	r   c                   @   s"   e Zd ZU dZeed< eed< dS )_ConstraintTargetz2
    This represents input tensor dimensions.
    t_idrm   N)r   r   r    r!   r=   __annotations__r%   r%   r%   r&   rt      s   
 rt   c                   @   s`   e Zd ZU dZeed< ded< dddZd	d
 Zdd Zdd Z	dd Z
dd Zed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.
    r.   r   constraint_ranger   Nc                 C   s`   ddl m} ddlm} ddlm} |d u r|}|| jj|||d@ dd}t| j	| j
| j|S )Nr   r   r(   ValueRangeslowerupperFvrZ	warn_only)%torch.fx.experimental.symbolic_shapesr   r-   r)   torch.utils._sympy.value_rangesr{   rx   r   rw   ru   rm   r.   )rX   r}   r~   r   r)   r{   rx   r%   r%   r&   _clone_with_range  s   z_Constraint._clone_with_rangec                 C      | j |dS )Nr}   r   rX   r}   r%   r%   r&   __ge__)     z_Constraint.__ge__c                 C   s   | j |d dS )Nr   r   r   r   r%   r%   r&   __gt__,     z_Constraint.__gt__c                 C   r   )Nr~   r   rX   r~   r%   r%   r&   __le__/  r   z_Constraint.__le__c                 C   s   | j |d dS )Nr   r   r   r   r%   r%   r&   __lt__2  r   z_Constraint.__lt__c                 C   s   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.)	TypeErrorrW   r%   r%   r&   __bool__5  s   z_Constraint.__bool__c                 C      | j | j| jjj| jjjdS N)ru   rm   rY   r[   ru   rm   rx   r   r}   r~   rW   r%   r%   r&   serializable_spec@  s
   
z_Constraint.serializable_spec)r   N)r   r   r    r!   rL   rv   r   r   r   r   r   r   r\   r   r%   r%   r%   r&   rw   	  s   
 
rw   c                   @   s*   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.
    r.   r   rx   valN)r   r   r    r!   rL   rv   r=   r%   r%   r%   r&   r   Q  s
   
 r   c                   @   sF   e Zd ZU dZeed< ded< eeef ed< e	ed< e
d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.
    r.   r   rx   rP   rM   c                 C   r   r   r   rW   r%   r%   r&   r   s  s
   z$_DerivedConstraint.serializable_specN)r   r   r    r!   rL   rv   r	   rt   r   r   r\   r   r%   r%   r%   r&   r   c  s   
 	r   c                   @   s   e Zd ZdZedd ZdS )_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                 C   s   | j | jdS )Nru   rm   r   rW   r%   r%   r&   r     s   z$_RelaxedConstraint.serializable_specN)r   r   r    r!   r\   r   r%   r%   r%   r&   r   ~  s    r   
constraintget_sourcesr   	shape_envr   source_pairs)r   r   derived_equalities)r   r   phantom_symbolsr   relaxed_sourcesc                    sP  || j | j}|sdS |^ }	| fdd|	D  t| trJ| j|v r?|| j \}
}||
|}	| fdd|	D  dS | j | jf|| j< dS t| trt| jtsa|| jj | jjd }n,| jj|v rn|| jj }n|j	| jj
tjj| jjtjjjjj| jjd}||| jj< | j}| ||f dS t| tr|  dS dS )z
    Updates `source_pairs`, `derived_equalities`, and `phantom_symbols` (which become
    fields of `EqualityConstraint`) based on a given input `constraint`.
    Nc                 3       | ]} |fV  qd S r4   r%   rp   Zother_sourcesourcer%   r&   rr         z&_process_equalities.<locals>.<genexpr>c                 3   r   r4   r%   r   r   r%   r&   rr     s    
r   )r   r   Zdynamic_dimZconstraint_dim)ru   rm   extend
isinstancerw   r.   r   rP   r   Zcreate_symbolr   torch_dynamor   ZConstantSourceZfxZexperimentalZsymbolic_shapesZ
DimDynamicr$   rx   rM   appendr   add)r   r   r   rn   r   r   r   r   sourcesZother_sourcesZshared_t_idZ
shared_dimrP   rM   r%   r   r&   _process_equalities  s<   




r   	tree_namefunctreedynamic_shapesr   c          	   
      s   dd fddzt |g|R diW S  tyf } zAd|jd v ra|s.J ds4J d	d
d fdd fdd t|d\}}|D ]}t|\}} ||g  qQ d}~w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                 S   s   t | tvS r4   )r
   r   )tr%   r%   r&   is_leaf  s   z$_tree_map_with_path.<locals>.is_leafc                    sH   t |}|tv rt t| |d g|R diS | |g|R  S )Nr   r   )r
   r   r   Z
flatten_fn)pathr   r   typ)fr   r   r%   r&   r     s   z_tree_map_with_path.<locals>.fr   Zmismatchr   z2Cannot be a mismatch if there is no dynamic_shapesz7Must provide a tree_name when there might be a mismatchc                 S   sB   | t u r
t|| S | ttfv r|d u sJ t|S td|  )NzDid not expect type )dictr   listrs   r   AssertionError)type_contextir%   r%   r&   _key  s   z!_tree_map_with_path.<locals>._keyc                    s,   ddl m}m} ||jd  d|  dd)Nr   	UserErrorUserErrorTypez,Detected mismatch between the structure of `z` and `dynamic_shapes`: dynamic_shapes_validationZ	case_name)torch._dynamo.excr   r   INVALID_INPUT)msgr   r   r   r%   r&   raise_mismatch_error  s   z1_tree_map_with_path.<locals>.raise_mismatch_errorc                    sp  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	d
| jD }n|j}t
t	| j|D ]\}\}}|||| j| j|g  qd S )N`z` is a z, but `dynamic_shapesz` is notz` has z elements, but `dynamic_shapesz	 elementsz` has keys c                    s   g | ]} | qS r%   r%   )rp   kZ_remapr%   r&   
<listcomp>6  s    z9_tree_map_with_path.<locals>._compare.<locals>.<listcomp>)r   r   r   r<   lenZchildren_specsr   sortedr   zip	enumerate)r   r   r   rendered_pathZdynamic_shapes_children_specsr   Ztree_Zdynamic_shapes_)_comparer   r   r   r   r&   r     s`   



z%_tree_map_with_path.<locals>._comparer   N)r   
ValueErrorargsr   )	r   r   r   r   e_Z	tree_specZ
other_treeZother_tree_specr%   )r   r   r   r   r   r   r   r&   _tree_map_with_path  s$   		+r   Fc                 C   s`   t | tr	|  } |s.t | tjjrt| jnt| }|d ur#|ni }|j	|i |j
S |S r4   )r   r   moduler   nnModulerh   	signatureforwardbind	arguments)r   r   kwargsZ_is_torch_jit_tracer   r%   r%   r&   _combine_argsI  s   
r   c                   @   s:   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZd
S )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                 C   s
   i | _ d S r4   )_shapesrW   r%   r%   r&   __init__p     
zShapesCollection.__init__c                 C   sl   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   Tensorr<   idr   )rX   r   shaperu   _shaper%   r%   r&   __setitem__s  s   


zShapesCollection.__setitem__c                 C   s&   t |}|| jvri | j|< | j| S r4   )r   r   )rX   r   ru   r%   r%   r&   __getitem__  s   


zShapesCollection.__getitem__c                 C   s
   t | jS r4   )r   r   rW   r%   r%   r&   __len__  r   zShapesCollection.__len__Nc                    sN   t   fdd}t|||}t||}tfdd jD r%td|S )zu
        Generates the :func:`dynamic_shapes` pytree structure according to :func:`args` and :func:`kwargs`.
        c                    s*   t |}| jv r|  j| S d S r4   )r   r   r   )r   r   ru   rX   t_idsr%   r&   
find_shape  s
   


z3ShapesCollection.dynamic_shapes.<locals>.find_shapec                 3   s    | ]}| vV  qd S r4   r%   )rp   ru   )r   r%   r&   rr     r   z2ShapesCollection.dynamic_shapes.<locals>.<genexpr>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   )rX   mr   r   r   combined_argsr   r%   r   r&   r     s   
zShapesCollection.dynamic_shapesr4   )	r   r   r    r!   r   r   r   r   r   r%   r%   r%   r&   r   Y  s    r   c                  C   s   d} t |  d S )NzTUsing None as a dynamic shape dimension is deprecated. Please use Dim.STATIC instead)logwarning)r   r%   r%   r&   %_warn_on_None_dynamic_shape_dimension  s   r   r   c                    s2  ddl m m |du st|dkrdS t|ttfr#t||  } i  fdd fddt|t	ttfs?J t|t	rt|
 }t| 
 }t|t|krd| d	| d
}t| dkr{|d |vr{t| |d  t	r{|d7 }n|d7 } j|dd fdd}t|| |dd dS )z
    Checks the dynamic_shapes specification for correctness,
    using combined args + kwargs as reference for inputs structure.
    r   r   Nc              	      s   | j v r:| j  \}}| j|ks| j|kr8t| 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   rY   r[   r'   r1   r   )rm   r/   r0   Zthis_Zthat_)r   r   boundsr%   r&   check_same_bounds  s   
	z0_check_dynamic_shapes.<locals>.check_same_boundsc                    s2  t |tr@| D ]4\}}t |tr| q	|d u rt  q	t |ttfs= jd| d| dt|  d| d	ddq	d S t |t	t
frt|D ]4\}}t |trY| qK|d u rat  qKt |ttfs jd| d| dt|  d	| d	ddqKd S |d ur jd
| dt|  dddd S )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   r=   r   r   r   rs   r   r   )r   tensorr   r   rm   )r   r   r   r%   r&   check_symbols  sV   




z,_check_dynamic_shapes.<locals>.check_symbolszWWhen `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                    s^   t |tjr| || d S |d ur-t| } jd| d| dt| d| d	ddd S )NzCannot associate shape r   z` to non-tensor type z at `inputsz` (expected None)r   r   )r   r   r   r   r   r<   )r   r   dynamic_shaper   )r   r   r   r%   r&   check_shape  s   z*_check_dynamic_shapes.<locals>.check_shapeinputsr   )r   r   r   r   r   rs   r   r<   valuesr   keysr   r   r   )r   r   Zgot_keysZexpected_arg_namesr   r   r%   )r   r   r   r   r   r&   _check_dynamic_shapes  sD   (
r  c                    s   ddl m m |du st|dkrg S t|ttfr#t||  } t	ti g g  fddfddfdd	}t
|| |d
d D ]}|jj}|v r`| d |_qO D ]}| qeS )zT
    Reads the dynamic_shapes specification and produces a list of constraints.
    r   r   Nc           
   	      sx  dd l ddlm} ddlm ddlm}  fdd}t tr j	}|j
	v r>	|j
 d }t|j|j}n#|j
vr\t|j
|||j|jddd	| d
}||j
< n|j
 }tt j
|| j jddd	| j}	t|tr|	 |	S t trtt j
|| j jddd	}	|	S t tsJ tt j
|| j jddd	}	|	S )Nr   ry   )	try_solverz   c                     st   j jjdd} | }|j | }|d ur$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   rP   r   rM   Eqr   r=   ZCONSTRAINT_VIOLATION)symbolexprZsolution)r   r   rm   r   rK   r   r  r%   r&   
root_value>  s   
zB_process_dynamic_shapes.<locals>.to_constraint.<locals>.root_valuer|   Fr   )r.   rx   r   )rK   r   r   Ztorch.utils._sympy.solver  r   r{   r   rQ   rP   r   rt   ru   rm   r   rY   r[   r   r   rM   r   rS   rw   rV   r'   )
rm   r   r   r   r{   r	  Zdim_rootZroot_constraintrP   r   )r   r   %derived_constraints_with_phantom_rootphantom_rootssymbols)rm   r   rK   r   r  r&   to_constraint7  st   






z._process_dynamic_shapes.<locals>.to_constraintc                    s0  dd }t  |_t  |_t  |_t  |_t  |_t|tr| D ]f\}}t|t	t
frFt|t	r7||||}|||}|j | q!t|tr||tjkrXtj|| n|tjkretj|| n|tjkrqtj||  tt|| q!|d u rtj|| q!d S t|ttfrt|D ]f\}}t|t	t
frt|t	r||||}|||}|j | qt|tr|tjkrtj|| n|tjkrtj|| n|tjkrtj||  tt|| q|d u rtj|| qd S |d u rt| D ]}tj|| q	d S d S )Nc                 S   s   t t|tfd|iS )NrV   )rS   rL   r=   )r   r   rV   r%   r%   r&   _create_static_dim  s   zK_process_dynamic_shapes.<locals>.update_symbols.<locals>._create_static_dim)r   Z_dynamo_weak_dynamic_indicesZ_dynamo_dynamic_indicesZ_dynamo_dynamic_rangeZ_dynamo_static_indicesZ_dynamo_unbacked_indicesr   r   r   r=   r'   r   r   r   r"   r   r   Zmaybe_mark_dynamicr#   Zmark_staticr$   Zmark_dynamicr   r   rs   r   r   rangerm   )r   r   r   r  r   rm   r   )constraintsr  r  r%   r&   update_symbols  sb   











z/_process_dynamic_shapes.<locals>.update_symbolsc                    s    t |tjr | || d S d S r4   )r   r   r   )r   r   r   )r  r%   r&   assoc_shape  s   z,_process_dynamic_shapes.<locals>.assoc_shaper   r   )r   r   r   r   r   rs   r   r<   r  r   r   rP   r.   r   )r   r   r  Z$derived_constraint_with_phantom_rootZphantom_root_nameZdynamic_dimsr%   )r   r   r  r
  r  r  r  r  r&   _process_dynamic_shapes   s*   S2r  c                 C   st   i }t | dd dd D ]+}|d u rqt|trqt|tr0|||j< t|tr/|j||jj< qt|ts7J q|S )Nc                 S   s
   t | tS r4   )r   r'   r5   r%   r%   r&   r9     s   
 z'_get_dim_name_mapping.<locals>.<lambda>r   r   )r   r   r=   r'   r   rQ   rP   r   )r   name_to_dimrm   r%   r%   r&   _get_dim_name_mapping  s$   



r  r   c              
      s  ddl }ddlddlm}m} ddlm} z| dd  }W n t	y4 } z||j
d|d}~ww i |dD ]\}| }|d	| }	r{|	d}
d
\}}|d| }rbt|d}|d| }rqt|d}t|
||d|
< q<|d\}
}|}t|jrt||
< q<||
< q<t|t } D ]8\}}t|tttjfsJ t|jr||sJ ||< |ttt|j t|tr||jj q D ]\}}|v s||v sJ qi   fdd}t|||S )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]+)\)rd   z = c           	         s,  |d u s	t |tr|S |jv ro|j }t |jrmt| v r' t| S tt|j}|jv r9|j }n|jv s@J |j }j	j
||\}}|}|dkr[t|| }|dkre|t| }| t|< |S |S t |tr|jjv r|j v r |j S ||jj }| |j< |S |S )Nr   r   )r   r=   r   ExprrL   nextiterfree_symbolsr.   ZpolysZ	polytoolsdivrQ   rP   rM   )	r   rm   dummyfixr  rP   modulus	remainderZ_dimZderived_dim_cacher  Zshape_fixesrK   r%   r&   apply_fixesC  s8   






z?refine_dynamic_shapes_from_suggested_fixes.<locals>.apply_fixes) rerK   r   r   r   r   r  splitstrip	Exceptionr   matchgroupr=   r   rJ   r   Numberr  r   r   r'   rQ   r  r   rL   r  r  r  rP   r   r   )r   r   r#  r   r   r  Zshape_fixes_msgexcr  r'  r.   rk   rl   Z	match_minZ	match_maxr  rootsr   cr"  r%   r!  r&   r     s`    



$r   )F)Gdataclassesrh   loggingra   collectionsr   enumr   r   typingr   r   r   r   r	   r   Ztorch.utils._pytreer
   r   r   r   r   r   r   r   r   Zexported_programr   rK   r   Ztorch._guardsr   r   r   r   __all__	getLoggerr   r   r   r<   r'   rS   rQ   rL   r=   r   r"   r#   r$   rs   r   	dataclassrt   rw   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r%   r%   r%   r&   <module>   s   ,
E&C

	G


?

|K	

s

 5
