
    Vh,                         d dl Z d dlmZmZmZ d dlZd dlmZmZ d dl	m
Z
mZmZmZmZmZ d dlmZ ddlmZ e j(                   G d d	             Ze j(                   G d
 d             Z	 ddeeeef   ee   ee   df   deeeeeeee   df   f   f   dee   deeeeef   f   fdZ	 	 ddeeeef   ee   ee   df   dee   deeeef      dee   deeeeef   f   f
dZ	 ddeeeeef   f   dee   deeeef   ee   ee   df   fdZy)    N)AnyOptionalUnion)	UserErrorUserErrorType)_check_dynamic_shapes_DerivedDim_Dim_DimHint_tree_map_with_pathDim)tree_map   )_dataclass_to_dictc                   @    e Zd ZU dZeed<   eedf   ed<   ee   ed<   y)RootDimz(
    This represents a _Dim object.
    minNmaxderived)	__name__
__module____qualname____doc__int__annotations__r   liststr     R/home/dcms/DCMS/lib/python3.12/site-packages/torch/_export/serde/dynamic_shapes.pyr   r      s'     
H	sDy	#Yr   r   c                   T    e Zd ZU dZeeeef   ee   e	e   df   e
d<   eeef   e
d<   y)DynamicShapesSpeczA
    This stores a dynamic_shapes spec for de/serialization.
    Ndynamic_shapesdims)r   r   r   r   r   dictr   r   tupler   r   r   r   r   r    r"   r"      s<     $sCx.%*d3iEFF
sG|
r   r"   r#   r$   to_dictreturnc                     ddl m} t        |j                               D ci c]/  \  }}|t	        |d   |d   |u rdn|d   t        |d               1 }}}t        | |      }|rt        |      S |S c c}}w )	z4
    Sorts dims and dumps to dictionary format.
    r   )int_oor   r   Nr   r   r   r   r#   r$   )torch.utils._sympy.numbersr*   sorteditemsr   r"   r   )r#   r$   r'   r*   kvspecs          r    _postprocess_serialized_shapesr3   (   s     2 4::<( Aq 	
7%%F*%1Y<(
 	
D  NFD!$''s   4A6argskwargsc                   	 i 	d }dt         dt        t        t        f   dt         dt        t        f   f	fd}| di dS |xs i }t        | t              r| j                         } t        |       } t        |      t        |j                               z   }t        t        t        |            |        t        ||| d      }t        ||      }t        |	|	      S )
ay  
    Utility function for dynamic shapes serialization, serializing a dynamic_shapes spec.
    Returns a DynamicShapesSpec dataclass containing 2 fields, "dynamic_shapes" and "dims".
    Uses args & kwargs to distinguish between tensor-level and dim-level specs (only for Nones).

    dynamic_shapes: A pytree structure mirroring the dynamic_shapes input to export():
        - Each tensor input is represented with a list of values, non-tensor inputs with None.
        - dynamic dimensions (i.e. symbols) in tensors and Dim enums are represented with strings.
        - static dimensions are represented with ints.

    dims: A dictionary mapping each symbol name to the min/max range and derived dim names.

    For example:
    ```
    dx = Dim("dx", min=4, max=16)
    dy = dx + 1

    inputs = (
        [
            torch.randn(4, 4),
            torch.randn(5, 4),
        ],
        torch.randn(4),
        torch.randn(4, 4),
        "hello",
    )
    dynamic_shapes = {
        "a": [
            (dx, 4),
            (dy, 4),
        ],
        "b": (Dim.STATIC,),
        "c": None,
        "d": None,
    }
    out = _dump_dynamic_shapes(dynamic_shapes, inputs, to_dict=True)
    ```
    would generate the following output:
    ```
    {
        'dynamic_shapes': (
            [
                ['dx', 4],
                ['dx + 1', 4],
            ],
            ['_DimHint.STATIC'],
            ['_DimHint.STATIC', '_DimHint.STATIC'],
            None,
        ),
        'dims': {
            'dx': {
                'min': 4,
                'max': 16,
                'derived': ['dx + 1'],
            },
        },
    }
    ```
    c                    t        |t        j                        sy|'t        j                  gt        |j                        z  S g }t        |t              rRt        |j                        D ]8  \  }}|j                  |j                  |      |n|j                  |             : |S t        |t        t        f      sJ t        |j                        D ]   \  }}|j                  ||   |n||          " |S )z
        Helps standardize the dynamic_shapes tree structure we serialize,
        returning lists for each tensor shape, handling tensor-level Nones.
        N)
isinstancetorchTensorr   STATIClenshaper%   	enumerateappendgetr&   r   )pathtensorr=   outiss         r    _standardize_shapesz1_dump_dynamic_shapes.<locals>._standardize_shapes   s    
 &%,,/=JJ<#fll"333eT"!&,,/ H1

		! 41%))A,GH 
 eeT]333!&,,/ @1

a 01eAh?@
r   valNr(   c                     | t        | t              r| S t        | t              r&| j                  j                  dz   | j
                  z   S t        | t              sJ t        | t              r| j                  n| }|j                  vr/|j                  |j                  t               d|j                  <   t        | t              r+|j                     d   j                  | j                         | j                  S )z^
        Tracks dims, ranges, derived dims from the standardized dynamic_shapes spec.
        .r+   r   )r8   r   r   	__class__r   namer
   r	   rootr   r   setadd)rG   rL   r$   s     r    _track_dim_from_dimsz2_dump_dynamic_shapes.<locals>._track_dim_from_dims   s     ;*S#.Jc8$==))C/#((::#t$$$ &c;7sxxS==$xxxx5#D c;'	*..s||<||r   r,   inputs)	tree_name)r'   )r   r   r   r
   r   r8   r%   valuesr&   r   r>   r   r   r3   )
r#   r4   r5   r'   rF   rO   combined_argstree_shapesserialized_shapesr$   s
            @r    _dump_dynamic_shapesrV   A   s    B ')D(4h,-	tS#~	8 "&33 \rF.$''..0>*N$K%"88M $y78.I%]NhK !!5{C)*;T7SSr   r2   	from_dictc           	         ddl }ddlm} |rt        | t              s&t        t        j                  dt        |              t        | j                               ddgk7  r+t        t        j                  d| j                                i | d   j                         D ]O  \  }}t        |t              s&t        t        j                  dt        |             t        |j                               g d	k7  r+t        t        j                  d
|j                                t        |d   t              s#t        t        j                  d| d|d          t        |d   t              r|d   #t        t        j                  d| d|d          t        |d   t              rt        d |d   D              r#t        t        j                  d| d|d          t!        di ||<   R | d   }nNt        | t"              s&t        t        j                  dt        |              | j$                  | j&                  }|yi j                         D ]U  \  }}|j)                  |      }	t        |	|j*                        st        t        j                  d|       t-        ||j.                  |j0                        |<   |j2                  D ]  }
|j)                  |
      }t5        |j6                        dk7  s|	|j6                  vr t        t        j                  d| d|        ||      st        t        j                  d|       |j8                  j:                  j=                  ||	      \  }}|   }|dk7  rt        |      |z  }|dk7  r|t        |      z   }||
<    X dt>        dt        t        f   dt>        dt        t@        tB        f   ffd}tE        ||      S )z
    Utility function for dynamic shapes serialization.
    Deserializes a DynamicShapesSpec or corresponding dictionary into a dynamic_shapes input to export().
    r   N)_is_supported_equivalencez7With from_dict=True, expected `spec` to be a dict, got r$   r#   z]With from_dict=True, expected `spec` to have keys `dims` and `dynamic_shapes`, instead found z@Expected `spec['dims']` keys to be strings for symbols, got key )r   r   r   zWExpected `spec['dims']` values to have keys `derived`, `max`, and `min`, instead found r   z<Expected dims in `spec['dims']` to map `min` to an int, got z: r   zDExpected dims in `spec['dims']` to map `max` to an int or None, got r   c              3   >   K   | ]  }t        |t                 y w)N)r8   r   ).0ds     r    	<genexpr>z'_load_dynamic_shapes.<locals>.<genexpr>   s      9+,Jq#&&9s   zWExpected dims in `spec['dims']` to map `derived` to a list of derived expressions, got z/Expected `spec` to be a DynamicShapesSpec, got z0Expected `spec['dims']` keys to be symbols, got )r   r   r   z(Expected derived expressions in to have z as the only free symbol, got z;Expected derived expressions to be linear expressions, got rG   r(   c                 H   | t        | t              r| S | dk(  rt        j                  S | dk(  rt        j                  S t        | t
              st        t        j                  d|        | vr.t        t        j                  d|  dj                                |    S )Nz_DimHint.AUTOz_DimHint.STATICzuExpected leaves in `spec['dynamic_shapes']` to be ints, None, Dim.AUTO/STATIC, symbols,  or derived expressions, got zOExpected dims in `spec['dynamic_shapes']` to be tracked in `spec['dims']`, got z which is not in )
r8   r   r   AUTOr;   r   r   r   INVALID_INPUTkeys)rG   	dim_cacher$   s    r    deserialize_shapez/_load_dynamic_shapes.<locals>.deserialize_shape*  s     ;*S#.JO#== %%??"#s#++003u6 
 i++e,TYY[M; 
 ~r   r   )#sympy%torch.fx.experimental.symbolic_shapesrY   r8   r%   r   r   r`   typer.   ra   r/   r   r   r   anyr   r"   r$   r#   sympifySymbolr   r   r   r   r<   free_symbolspolys	polytoolsdivr   r
   r   r   )r2   rW   rd   rY   r0   r1   r#   rK   infosymbol_exprexprmodulus	remainderddimrc   rb   r$   s                   @@r    _load_dynamic_shapesru      s    O$%++I$t*V  $))+6+;"<<++!!%/ 
 L&&( 	#DAqa%!//VW[\]W^V_`  affh#<<!//%%&VVXJ0 
 ah,!//RSTRUUWXYZ_X`Wab  ah,%0@!//Z[\Z]]_`abg`h_ij  a	lD1S 901)9 6  !//#R)~/ 
 llDG=	#> ./$ 12++A$t*N  yy,,Ijjl $
dt$&%,,/++B4&I  ddhh?	$\\ 	$E=='D4$$%*fD<M<M.M!//>tfDbcgbhi  -T2!//QRVQWX  "'!6!6!:!:4!HGYT?D!|7|d*A~c)n,#Ie%	$$84c>"	tS$(	). %~66r   )F)NF) dataclassestypingr   r   r   r9   torch._dynamo.excr   r   torch.export.dynamic_shapesr   r	   r
   r   r   r   torch.utils._pytreer   	serializer   	dataclassr   r"   r%   r   r&   r   r   boolr3   rV   ru   r   r   r    <module>r~      s    ' '  6  ) )       $$sCx.%*d3iEF
sDeCcD$899::
; d^ d38n,-	8 (,#	DT$sCx.%*d3iEFDT
*DT T#s(^$DT d^	DT
 d38n,-DTR !&y7
!4S>1
2y7~y7 4S>5:tCy$67y7r   