a
    h                  
   @   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mZ ddlmZ erd 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(e j)G dd dZ*G dd dZ+e+Z,G dd de+Z-G dd de+Z.ddde/ee0 ee0 e1e+df dddZ2e j)G dd dZ3e j)G dd de3Z4e j)G dd  d Z5e j)G d!d" d"e3Z6e j)G d#d$ d$e3Z7ee4e6e7f Z8e j)G d%d& d&Z9e8ee0e0ge:d' f d(e;e/e1e0e0f f e:e1d)  e:e1d'ed* ef  e;e/d+f e<d' d,d-d.Z=dd/ede
f e
e
ee/ e
d0d1d2Z>dIe;e/e
f d4d5d6Z?G d7d8 d8Z@G d9d: d:ZAd;d< ZBe;e/e
f ee;e/e
f e1e
 e:e
 df d=d>d?ZCe;e/e
f ee;e/e
f e1e
 e:e
 df e:e8 d@dAdBZDee;e/e
f e1e
 e:e
 df dCdDdEZEe/ee;e/e
f e1e
 e:e
 f ee;e/e
f e1e
 e:e
 f dFdGdHZFdS )J    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tree_map_with_path   )ExportedProgram)Symbol)Source)ShapeEnvStrictMinMaxConstraint)
ConstraintDimdims*refine_dynamic_shapes_from_suggested_fixesAdditionalInputsc                   @   s"   e Zd ZdZe Ze Ze ZdS )_DimHintTypez
    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'   I/var/www/auris/lib/python3.9/site-packages/torch/export/dynamic_shapes.pyr   -   s   r   c                   @   sz   e Zd ZU eed< dZee ed< dZee ed< dZ	ee
 ed< edd Zed	d
 Zedd Zdd dddZdS )_DimHinttypeNminmaxT_factoryc                   C   s
   t tjS N)r)   r   r$   r'   r'   r'   r(   r$   A   s    z_DimHint.AUTOc                   C   s
   t tjS r.   )r)   r   r&   r'   r'   r'   r(   r&   E   s    z_DimHint.DYNAMICc                   C   s
   t tjS r.   )r)   r   r%   r'   r'   r'   r(   r%   I   s    z_DimHint.STATICreturnc                 C   s|   | j stdt|  d|d u s2|dks2J d|d u sJ|dksJJ d|d u sj|d u sj||ksjJ dt| j||ddS )	N'z' object is not callabler   zmin must be non-negativezmax must be non-negativezmin must be <= maxF)r+   r,   r-   )r-   	TypeErrorr*   r)   )selfr+   r,   r'   r'   r(   __call__M   s     z_DimHint.__call__)NN)r    r!   r"   r   __annotations__r+   r   intr,   r-   boolstaticmethodr$   r&   r%   r4   r'   r'   r'   r(   r)   :   s   



r)   c                   @   s   e Zd ZdZe Ze Ze Zdddee	e
 e	e
 dddZd ddd	Zd dd
dZd dddZd dddZd dddZd dddZedddZd dddZeee
e
edddZdd ZdS )r   a
  
    The `Dim` class allows users to specify dynamism in their exported programs. By marking a dimension with a `Dim`,
    the compiler associates the dimension with a symbolic integer containing a dynamic range.

    The API can be used in 2 ways: Dim hints (i.e. automatic dynamic shapes: `Dim.AUTO`, `Dim.DYNAMIC`, `Dim.STATIC`),
    or named Dims (i.e. `Dim("name", min=1, max=2)`).

    Dim hints provide the lowest barrier to exportability, with the user only needing to specify if a dimension
    if dynamic, static, or left for the compiler to decide (`Dim.AUTO`). The export process will automatically
    infer the remaining constraints on min/max ranges and relationships between dimensions.

    Example::

        class Foo(nn.Module):
            def forward(self, x, y):
                assert x.shape[0] == 4
                assert y.shape[0] >= 16
                return x @ y


        x = torch.randn(4, 8)
        y = torch.randn(8, 16)
        dynamic_shapes = {
            "x": {0: Dim.AUTO, 1: Dim.AUTO},
            "y": {0: Dim.AUTO, 1: Dim.AUTO},
        }
        ep = torch.export(Foo(), (x, y), dynamic_shapes=dynamic_shapes)

    Here, export would raise an exception if we replaced all uses of `Dim.AUTO` with `Dim.DYNAMIC`,
    as x.shape[0] is constrained to be static by the model.

    More complex relations between dimensions may also be codegened as runtime assertion nodes by the compiler,
    e.g. (x.shape[0] + y.shape[1]) % 4 == 0, to be raised if runtime inputs do not satisfy such constraints.

    You may also specify min-max bounds for Dim hints, e.g. `Dim.AUTO(min=16, max=32)`, `Dim.DYNAMIC(max=64)`,
    with the compiler inferring the remaining constraints within the ranges. An exception will be raised if
    the valid range is entirely outside the user-specified range.

    Named Dims provide a stricter way of specifying dynamism, where exceptions are raised if the compiler
    infers constraints that do not match the user specification. For example, exporting the previous
    model, the user would need the following `dynamic_shapes` argument::

        s0 = Dim("s0")
        s1 = Dim("s1", min=16)
        dynamic_shapes = {
            "x": {0: 4, 1: s0},
            "y": {0: s0, 1: s1},
        }
        ep = torch.export(Foo(), (x, y), dynamic_shapes=dynamic_shapes)

    Named Dims also allow specification of relationships between dimensions, up to univariate linear relations.
    For example, the following indicates one dimension is a multiple of another plus 4::

        s0 = Dim("s0")
        s1 = 3 * s0 + 4

    Nr+   r,   )namer+   r,   c                C   st   ddl m} |d u rdn|}|d u r(|n|}||ksHJ d| d| | s^J d| || _|| _|| _d S )Nr   int_ooz(Cannot create Dim with inconsistent min=, max=z)Dim name must be a valid identifier, got )torch.utils._sympy.numbersr<   isidentifierr    r+   r,   )r3   r:   r+   r,   r<   _min_maxr'   r'   r(   __init__   s    zDim.__init__r/   c                    s6   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 r.   r'   xotherr'   r(   <lambda>       zDim.__add__.<locals>.<lambda>r*   r6   NotImplementedErrorr    _deriver3   rG   r'   rF   r(   __add__   s
    zDim.__add__c                 C   s   | | S r.   r'   rM   r'   r'   r(   __radd__   s    zDim.__radd__c                    s6   t  tur$td  d| j d|  fddS )NzAttempted to subtract z from rC   c                    s   |   S r.   r'   rD   rF   r'   r(   rH      rI   zDim.__sub__.<locals>.<lambda>rJ   rM   r'   rF   r(   __sub__   s
    zDim.__sub__c                 C   s   t d| j dd S )NzAttempted to negate zN. (Only increasing linear operations with integer coefficients are supported.))rK   r    rM   r'   r'   r(   __rsub__   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 r.   r'   rD   rF   r'   r(   rH      rI   zDim.__mul__.<locals>.<lambda>rJ   rM   r'   rF   r(   __mul__   s
    zDim.__mul__c                 C   s   | | S r.   r'   rM   r'   r'   r(   __rmul__   s    zDim.__rmul__c                 C   s   ddl m} t||| jS )Nr   )sympify)sympyrT   strr    )r3   fnrT   r'   r'   r(   _derived_name   s    zDim._derived_namec                 C   s   t | || |S r.   )_DerivedDimrX   r3   rW   r'   r'   r(   rL      s    zDim._derive)r:   min_max_r0   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 rZd|  d| dS |d u rtd|  d| dS d|  d| d	| dS )
Nr   r;      zDim('z')z', max=)z', min=r=   )r>   r<   )r:   r[   r\   r<   r'   r'   r(   	_readable   s    zDim._readablec                 C   s   t | j| j| jS r.   )r   r_   r    r+   r,   r3   r'   r'   r(   __repr__   s    zDim.__repr__)r    r!   r"   r#   r)   r$   r&   r%   rV   r   r6   rB   rN   rO   rP   rQ   rR   rS   rX   rL   r8   r_   ra   r'   r'   r'   r(   r   V   s&   :			r   c                   @   s6   e Zd ZdZedddZedd Zedd Zd	S )

_StaticDimz
    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.
    valuec                 C   s   t || _|| _d S r.   )rV   r    rd   )r3   rd   r'   r'   r(   rB      s    
z_StaticDim.__init__c                 C   s   | j S r.   rc   r`   r'   r'   r(   r+      s    z_StaticDim.minc                 C   s   | j S r.   rc   r`   r'   r'   r(   r,      s    z_StaticDim.maxN)	r    r!   r"   r#   r6   rB   propertyr+   r,   r'   r'   r'   r(   rb      s   
rb   c                   @   sJ   e Zd ZdZeeedddZedd Z	edd Z
d	d
 Zdd ZdS )rY   a  
    Class 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`.
    )r:   rootrW   c                 C   s   || _ || _|| _d S r.   )r    rf   rW   )r3   r:   rf   rW   r'   r'   r(   rB     s    z_DerivedDim.__init__c                 C   sv   ddl m} ddlm} | jj| u r,| S | || jj}| j}|dksnJ 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 ).)	rU   rh   r>   r<   rf   r+   rW   r    r6   )r3   rh   r<   Z_min_symintrf   r'   r'   r(   r+     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   rg   r;   r   zExpected derived max value of z
 to be <= z.. Please specify an appropriate max value for ri   rj   )rU   rh   r>   r<   rf   r,   rW   sysmaxsizer    r6   )r3   rh   r<   Z_max_symintrf   r'   r'   r(   r,   &  s    z_DerivedDim.maxc                    s   t  j fddS )Nc                    s     | S r.   )rW   rD   rW   r3   r'   r(   rH   A  rI   z%_DerivedDim._derive.<locals>.<lambda>)rY   rX   rf   rZ   r'   rm   r(   rL   :  s
    z_DerivedDim._derivec                 C   s   | j S r.   )r    r`   r'   r'   r(   ra   D  s    z_DerivedDim.__repr__N)r    r!   r"   r#   rV   r   r   rB   re   r+   r,   rL   ra   r'   r'   r'   r(   rY      s   


rY   r9   .)namesr+   r,   r0   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 )r9   N)r   ).0r:   r,   r+   r'   r(   	<genexpr>Q  rI   zdims.<locals>.<genexpr>)tuple)r+   r,   rn   r'   rp   r(   r   H  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_iddimN)r    r!   r"   r#   r6   r5   r'   r'   r'   r(   rs   T  s   
rs   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 r0|}|| 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_rangesrz   rw   r   rv   rt   ru   r:   )r3   r|   r}   r   r<   rz   rw   r'   r'   r(   _clone_with_rangej  s    z_Constraint._clone_with_rangec                 C   s   | j |dS )Nr|   r   r3   r|   r'   r'   r(   __ge__~  s    z_Constraint.__ge__c                 C   s   | j |d dS )Nr   r   r   r   r'   r'   r(   __gt__  s    z_Constraint.__gt__c                 C   s   | j |dS )Nr}   r   r3   r}   r'   r'   r(   __le__  s    z_Constraint.__le__c                 C   s   | j |d dS )Nr   r   r   r   r'   r'   r(   __lt__  s    z_Constraint.__lt__c                 C   s   t dd S )NzCannot determine truth value of _Constraint. If you are trying to combine _Constraint's with logical connectives, you can specify them separately instead.)r2   r`   r'   r'   r(   __bool__  s    z_Constraint.__bool__c                 C   s   | j | j| jjj| jjjdS N)rt   ru   r+   r,   rt   ru   rw   r   r|   r}   r`   r'   r'   r(   serializable_spec  s
    
z_Constraint.serializable_spec)r   N)r    r!   r"   r#   rV   r5   r   r   r   r   r   r   re   r   r'   r'   r'   r(   rv   ^  s   

rv   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   rw   valN)r    r!   r"   r#   rV   r5   r6   r'   r'   r'   r(   r     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   rw   rf   rW   c                 C   s   | j | j| jjj| jjjdS r   r   r`   r'   r'   r(   r     s
    z$_DerivedConstraint.serializable_specN)r    r!   r"   r#   rV   r5   r	   rs   r   r   re   r   r'   r'   r'   r(   r     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rt   ru   r   r`   r'   r'   r(   r     s    z$_RelaxedConstraint.serializable_specN)r    r!   r"   r#   re   r   r'   r'   r'   r(   r     s   r   c                   @   s<   e Zd ZU dZeed< ejdddZe	e
eef  ed< dS )_IntWrapperz
    Dummy wrapper class to wrap around integer inputs so that when we parse the
    dynamic_shapes structure, we can mark if any of the integers were marked as
    dynamic.
    r   FN)initdefaultdynamism)r    r!   r"   r#   r6   r5   dataclassesfieldr   r   r	   r)   r'   r'   r'   r(   r     s
   
r   r   r   )r   r   )r   r   r   )
constraintget_sources	shape_envrn   source_pairsderived_equalitiesphantom_symbolsrelaxed_sourcesc                    sJ  || j | j}|sdS |^ }	| fdd|	D  t| tr| j|v r||| j \}
}||
|}	| fdd|	D  n| j | jf|| j< nt| tr0t| jts|| jj | jjd }nX| jj|v r|| jj }n>|j	| jj
tjj| jjtjjjjj| jjd}||| jj< | j}| ||f nt| trF|  dS )z
    Updates `source_pairs`, `derived_equalities`, and `phantom_symbols` (which become
    fields of `EqualityConstraint`) based on a given input `constraint`.
    Nc                 3   s   | ]} |fV  qd S r.   r'   ro   Zother_sourcesourcer'   r(   rq     rI   z&_process_equalities.<locals>.<genexpr>c                 3   s   | ]} |fV  qd S r.   r'   r   r   r'   r(   rq     s   r   )r   r   Zdynamic_dimZconstraint_dim)rt   ru   extend
isinstancerv   r:   r   rf   r   Zcreate_symbolr   torch_dynamor   ZConstantSourceZfxZexperimentalZsymbolic_shapesZ
DimDynamicr&   rw   rW   appendr   add)r   r   r   rn   r   r   r   r   sourcesZother_sourcesZshared_t_idZ
shared_dimrf   rW   r'   r   r(   _process_equalities  s:    



r   	tree_name)functreedynamic_shapesr   r0   c          	   
      s   dd fddzt |g|R diW S  ty } zd|jd v r|s\J dshJ d	d
d fdd fdd t|d\}}|D ]}t|\}} ||g  q W Y d}~n
d}~0 0 dS )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 r.   )r
   r   )tr'   r'   r(   is_leafJ  s    z$_tree_map_with_path.<locals>.is_leafc                    sL   t |}|tv r6t t| |d g|R diS | |g|R  S d S )Nr   r   )r
   r   r   Z
flatten_fn)pathr   r   typ)fr   r   r'   r(   r   Q  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   sF   | t u rt|| S | ttfv r4|d u s,J t|S td|  d S )NzDid not expect type )dictr   listrr   r   AssertionError)type_contextir'   r'   r(   _keyi  s    z!_tree_map_with_path.<locals>._keyc                    s0   ddl m}m} ||jd  d|  ddd S )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_errorr  s    z1_tree_map_with_path.<locals>.raise_mismatch_errorc                    sv  t |}t| trd S t|trBd | d| j d| d | j|jkrvd | d| j d| d|j 	 t| jt|jkrd | dt| j d| dt|j d
 | jtu r.t| 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  qDd 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'   )ro   kZ_remapr'   r(   
<listcomp>  rI   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_path1  s     		+r   Fr/   c                 C   s`   t | tr|  } |s\t | tjjr0t| jnt| }|d urF|ni }|j	|i |j
S |S r.   )r   r   moduler   nnModuleinspect	signatureZforwardbind	arguments)r   r   kwargsZ_is_torch_jit_tracer   r'   r'   r(   _combine_args  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 )ShapesCollectiona*  
    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)

    To specify dynamism for integers, we need to first wrap the integers using
    _IntWrapper so that we have a "unique identification tag" for each integer.

    Example::

        args = {"x": tensor_x, "others": [int_x, int_y]}
        # Wrap all ints with _IntWrapper
        mapped_args = pytree.tree_map_only(int, lambda a: _IntWrapper(a), args)

        dynamic_shapes = torch.export.ShapesCollection()
        dynamic_shapes[tensor_x] = (dim, dim + 1, 8)
        dynamic_shapes[mapped_args["others"][0]] = Dim.DYNAMIC

        # This is equivalent to the following (now auto-generated):
        # dynamic_shapes = {"x": (dim, dim + 1, 8), "others": [Dim.DYNAMIC, None]}

        torch.export(..., args, dynamic_shapes=dynamic_shapes)
    c                 C   s
   i | _ d S r.   )_shapesr`   r'   r'   r(   rB     s    zShapesCollection.__init__c                 C   sn   t |tjtfs"J dt| t|}|| jv r\| j| }||ksjJ d| d| n|| jt|< d S )Nz:Cannot assign shape to non-tensor or non-_IntWrapper type z0Shapes assigned to input do not match: expected z, got )r   r   Tensorr   r*   idr   )r3   r   shapert   Z_shaper'   r'   r(   __setitem__  s    


zShapesCollection.__setitem__c                 C   s&   t |}|| jvri | j|< | j| S r.   )r   r   )r3   r   rt   r'   r'   r(   __getitem__  s    

zShapesCollection.__getitem__c                 C   s
   t | jS r.   )r   r   r`   r'   r'   r(   __len__  s    zShapesCollection.__len__Nc                    sN   t   fdd}t|||}t||}tfdd jD rJt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 d S r.   )r   r   r   )r   r   rt   r3   t_idsr'   r(   
find_shape	  s
    


z3ShapesCollection.dynamic_shapes.<locals>.find_shapec                 3   s   | ]}| vV  qd S r.   r'   )ro   rt   )r   r'   r(   rq     rI   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   )r3   mr   r   r   combined_argsr   r'   r   r(   r     s    
zShapesCollection.dynamic_shapes)N)	r    r!   r"   r#   rB   r   r   r   r   r'   r'   r'   r(   r     s   (r   c                   @   s4   e Zd ZdZdd ZdddZdddZd	d
 ZdS )r   aQ  
    Infers dynamic_shapes based on additional inputs.

    This is useful particularly for deployment engineers who, on the one hand, may
    have access to ample testing or profiling data that can provide a fair sense of
    representative inputs for a model, but on the other hand, may not know enough
    about the model to guess which input shapes should be dynamic.

    Input shapes that are different than the original are considered dynamic; conversely,
    those that are the same as the original are considered static. Moreover, we verify
    that the additional inputs are valid for the exported program. This guarantees that
    tracing with them instead of the original would have generated the same graph.

    Example::

        args0, kwargs0 = ...  # example inputs for export

        # other representative inputs that the exported program will run on
        dynamic_shapes = torch.export.AdditionalInputs()
        dynamic_shapes.add(args1, kwargs1)
        ...
        dynamic_shapes.add(argsN, kwargsN)

        torch.export(..., args0, kwargs0, dynamic_shapes=dynamic_shapes)
    c                 C   s
   g | _ d S r.   )	_examplesr`   r'   r'   r(   rB   7  s    zAdditionalInputs.__init__Nc                 C   sT   t |tu sJ d| d|du s@t |tu s@J d| d| j||f dS )zC
        Additional input :func:`args` and :func:`kwargs`.
        zRepresentative args z must be a tupleNzRepresentative kwargs z must be None or a dict)r*   rr   r   r   r   )r3   r   r   r'   r'   r(   r   :  s
    
zAdditionalInputs.addc                    sF    fdd||fg| j D ^}}dd }t||g|R ddd iS )z
        Infers a :func:`dynamic_shapes` pytree structure by merging shapes of the
        original input :func:`args` and :func:`kwargs` and of each additional input
        args and kwargs.
        c                    s&   g | ]\}}t d d t ||qS )c                 S   s   t |tjrt|jS |S r.   )r   r   r   rr   r   )r   r   r'   r'   r(   rH   N  rI   z<AdditionalInputs.dynamic_shapes.<locals>.<listcomp>.<lambda>)r   r   )ro   r   r   r   r'   r(   r   L  s
   
z3AdditionalInputs.dynamic_shapes.<locals>.<listcomp>c                    s   t  fdd|D s,td f|  dt trbt tsbt  fdd|D rZd S tjS n0t  fdd|D std f|  dd S d S )Nc                 3   s   | ]}t  t |kV  qd S r.   )r*   )ro   rG   vr'   r(   rq   U  rI   zJAdditionalInputs.dynamic_shapes.<locals>._mark_dynamism.<locals>.<genexpr>z^The following inputs were found to have differing types, so they cannot be marked as dynamic: .c                 3   s   | ]}| kV  qd S r.   r'   ro   Zother_vr   r'   r(   rq   \  rI   c                 3   s   | ]}| kV  qd S r.   r'   r   r   r'   r(   rq   a  rI   z`The following inputs were found to have differing values, but they cannot be marked as dynamic: )allr   r   r6   r7   r   r&   )r   Zother_vsr'   r   r(   _mark_dynamismT  s"    z7AdditionalInputs.dynamic_shapes.<locals>._mark_dynamismr   c                 S   s   t | tu S r.   )r*   r6   )r   r'   r'   r(   rH   l  rI   z1AdditionalInputs.dynamic_shapes.<locals>.<lambda>)r   r   )r3   r   r   r   r   Zother_dynamic_shapesr   r'   r   r(   r   E  s    

zAdditionalInputs.dynamic_shapesc                 C   s2   |  }| jD ]\}}tjj|||p(i  qdS )zW
        Verifies that an exported program is valid for each additional input.
        N)r   r   r   exportZ_unliftZ!_check_input_constraints_pre_hook)r3   epZepmr   r   r'   r'   r(   verifyo  s
    
zAdditionalInputs.verify)N)N)r    r!   r"   r#   rB   r   r   r   r'   r'   r'   r(   r     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   r   c                    s6  ddl m m |du s$t|dkr(dS t|ttfrFt||  } i  fdd fddt|t	ttfs~J t|t	rt|
 }t| 
 }t|t|krd| d	| d
}t| dkr|d |vrt| |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 rr| j  \}}| j|ks,| j|krt| j ||}t| j | j| j} jd| d| d|  dn| j| jf| j < d S )NzFound different definitions z and z! for the same symbolic dimension !)r    r+   r,   r   r_   r   )ru   r[   r\   Zthis_Zthat_)r   r   boundsr'   r(   check_same_bounds  s    
z0_check_dynamic_shapes.<locals>.check_same_boundsc                    s  t |tr| D ]h\}}t |tr.| q|d u r>t  qt |ttfs jd| d| dt|  d| d	ddqnt |t	t
frZt|t|jkr jd| dt|  d	|j d
t|j dt| dddt|D ]l\}}t |tr| q|d u rt  qt |ttfs jd| d| dt|  d| d	ddqn,|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Expected dynamic shape spec z5` to have the same length as the actual tensor shape z (expected z
, but got 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   r6   r)   r   r   rr   r   r   r   r   r   tensorr   r   ru   )r   r   r   r'   r(   check_symbols  sd    






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| || nvt |trRt |tr6td|d u st |ttfsJ n>|d urt| } j	d| d| dt
| d| d	ddd S )	NzdUnable to specify input integers as dynamic through named Dims. Please use Dim.AUTO/DYNAMIC instead.zCannot associate shape r   z` to non-tensor type z at `inputsz` (expected None)r   r   )r   r   r   r   _Dimr   r6   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   rr   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  sH    0

r  )r   r   r0   c                    s   ddl m m |du s$t|dkr(g S t|ttfrFt||  } t	ti g g  fddddfddfd	d
fdd}t
|| |dd D ]"}|jj}|v r| d |_q D ]}| q܈S )zT
    Reads the dynamic_shapes specification and produces a list of constraints.
    r   r   Nc           
   	      s|  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}nF|j
vrt|j
|||j|jddd	| d
}||j
< n
|j
 }tt j
|| j jddd	| j}	t|trx|	 nnt tr@tt j
|| j jddd	}	n8t tsPJ tt j
|| j jddd	}	|	S )Nr   rx   )	try_solvery   c                     sx   j jjdd} | }|j | }|d urHt|d S  jd dj  d| d|  d	d S )	NT)integerr   zExpected shape[z] = z# of input Tensor to be of the form z, where z is an integer)r   rf   r    rW   Eqr   r6   ZCONSTRAINT_VIOLATION)symbolexprZsolution)r   r   ru   r   rU   r  r  r'   r(   
root_value$  s    
zB_process_dynamic_shapes.<locals>.to_constraint.<locals>.root_valuer{   Fr~   )r:   rw   r   )rU   r   r   Ztorch.utils._sympy.solver  r   rz   r   rY   rf   r    rs   rt   ru   r   r+   r,   r   r   rW   r   rb   rv   rd   r   )
ru   r  r   r   rz   r  Zdim_rootZroot_constraintrf   r   )r   r   %derived_constraints_with_phantom_rootphantom_rootssymbols)ru   r   rU   r  r  r(   to_constraint  st    



	z._process_dynamic_shapes.<locals>.to_constraintr/   c                    s   dd }t |ttfrJt |tr,|| ||}|| |}|j | nt |tr|jtjkrpt	j
| | n6|jtjkrt	j
| | n|jtjkrt	j
| |  tt| | n|d u rt	j
| | d S )Nc                 S   s   t |S r.   )rb   )r  r   rd   r'   r'   r(   _create_static_dims  s    zN_process_dynamic_shapes.<locals>._parse_tensor_dim.<locals>._create_static_dim)r   r6   r   r    r   r)   r*   r   r$   r   r   Zmaybe_mark_dynamicr%   Zmark_staticr&   Zmark_dynamicr   r   )r  idxru   r  r   )constraintsr  r  r'   r(   _parse_tensor_dimr  s     

z2_process_dynamic_shapes.<locals>._parse_tensor_dimc                    s   t  |_t  |_t  |_t  |_t  |_t|trR| D ]\}} ||| q:nTt|t	t
frt|D ]\}} ||| qhn&|d u rt| D ]} ||d  qd S r.   )r   Z_dynamo_weak_dynamic_indicesZ_dynamo_dynamic_indicesZ_dynamo_dynamic_rangeZ_dynamo_static_indicesZ_dynamo_unbacked_indicesr   r   r  rr   r   r   rangeru   r  )r  r'   r(   update_symbols  s    
z/_process_dynamic_shapes.<locals>.update_symbolsc                    s.   t |tjr | || nt |tr*||_d S r.   )r   r   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   rr   r   r*   r	  r   r   rf   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  r(   _process_dynamic_shapes  s*    Ur  )r   c                 C   sv   i }t | dd dd D ]X}|d u r&qt|tr4qqt|trb|||j< t|trp|j||jj< qt|tsJ q|S )Nc                 S   s
   t | tS r.   )r   r   rD   r'   r'   r(   rH     rI   z'_get_dim_name_mapping.<locals>.<lambda>r   r   )r   r   r6   r   r    rY   rf   r)   )r   name_to_dimru   r'   r'   r(   _get_dim_name_mapping  s"    



r  )r   r   r0   c              
      s"  ddl }ddlddlm}m} ddlm} z| dd  }W n2 t	yt } z||j
d|W Y d}~n
d}~0 0 i |dD ]}| }|d	| }	r|	d}
d
\}}|d| }rt|d}|d| }rt|d}t|
||d|
< q|d\}
}|}t|jr8t||
< q||
< qt|t } D ]z\}}t|tttjfszJ t|jr||sJ ||< |ttt|j t|trX||jj qX 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]+)\)r9   z = c           	         s6  |d u st |tr|S |jv r|j }t |jrt| v rN t| S tt|j}|jv rr|j }n|jv sJ |j }j	j
||\}}|}|dkrt|| }|dkr|t| }| t|< |S n|S nPt |tr2|jjv r2|j v r |j S ||jj }| |j< |S |S )Nr   r   )r   r6   r    ExprrV   nextiterfree_symbolsr:   ZpolysZ	polytoolsdivrY   rf   rW   )	r   ru   dummyfixr  rf   modulus	remainderZ_dimZderived_dim_cacher  Zshape_fixesrU   r'   r(   apply_fixes'  s8    





z?refine_dynamic_shapes_from_suggested_fixes.<locals>.apply_fixes)rerU   r   r   r   r   r   splitstrip	Exceptionr   matchgroupr6   r   rT   r   Numberr  r   r  rY   r"  r   rV   r#  r$  r%  rf   r    r   )r   r   r-  r   r   r   Zshape_fixes_msgexcr(  r1  r:   r@   rA   Z	match_minZ	match_maxr  rootsr   cr,  r'   r+  r(   r     sX     


$r   )F)Gr   r   loggingrk   collectionsr   enumr   r   typingr   r   r   r   r	   r   Ztorch.utils._pytreer
   r   r   r   r   r   r   r   r   r   Zexported_programr   rU   r   Ztorch._guardsr   r   r   r   __all__	getLoggerr    r   r   Z	dataclassr)   r   r  rb   rY   rV   r6   rr   r   rs   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r'   r'   r'   r(   <module>   s   0	
 L
	G

?
|__

 
 4