
    Vh0                        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Zd dlmZm	Z	m
Z
mZ d dlmZ ej                  Z ed      dddej                  d	ee   d
efd       Zdeeej$                  f   dedededef
dZd Ze
dej,                  e
   dee
   dedededej4                  diZd Z e       Zdej<                  d
efdZdee    d
ee   fdZ!y)    N)GenericAlias)OptionalUnion)devicedtypeTensortypes)
exposed_inztorch.library)op_nameprototype_functionr   returnc               h	   d}| j                   dt        j                  |       fddt        ffddt        t
        t        t           t        f   df   dt        t        t        j                  df   t        f   ffd	d
t
        t        t           t        f   dt        t        j                  t        f   ffdg }t               }d}t        j                  j                               D ]3  \  }\  }}	t        |	      s d       |	j                   t        j"                  j$                  k(  r|s|j'                  d       d}|	j(                  t        j"                  j*                  u r d| d        |	j(                        \  }
}|
t,        vr|
j.                  t        u r[t1        |
      }d}|t,        j3                         v rd| d} d| d|	j(                   d| dt,        j3                          d	       n. d| d|	j(                   dt,        j3                          d       t,        |
   }t        |      t        k(  r6||k7  rt5        d      |j7                  d      rJd| d|t9        d      d  }n5||v r1|j7                  d      s d| d       d| d|t9        d      d  }|j;                  |       |	j<                  t        j"                  j*                  u r|j'                  | d|        d}|	j<                  %t?        |	j<                  t@        tB        t        f      rt        |	j<                        }nt?        |	j<                  t        tD        jF                  f      rd |	j<                   d }nt?        |	j<                  tD        jH                        r9t        |	j<                        }d!}|j7                  |      sJ |t9        |      d }n" d| d"t        |	j<                         d#       |j'                  | d| d$|        6 ||k7  r't        |      |z
  }t9        |      d%kD  r | d&        jJ                        \  }}tM        |      }|| d'd(jO                  |       d)| S d'd(jO                  |       d)| S )*aJ  Parses the schema of a given function with type hints. The schema is inferred from the
    function's type hints, and can be used to define a new operator.

    We make the following assumptions:

    * None of the outputs alias any of the inputs or each other.
    * | String type annotations "device, dtype, Tensor, types" without library specification are
      | assumed to be torch.*. Similarly, string type annotations "Optional, List, Sequence, Union"
      | without library specification are assumed to be typing.*.
    * | Only the args listed in ``mutates_args`` are being mutated. If ``mutates_args`` is "unknown",
      | it assumes that all inputs to the operator are being mutates.

    Callers (e.g. the custom ops API) are responsible for checking these assumptions.

    Args:
        prototype_function: The function from which to infer a schema for from its type annotations.
        op_name (Optional[str]): The name of the operator in the schema. If ``name`` is None, then the
            name is not included in the inferred schema. Note that the input schema to
            ``torch.library.Library.define`` requires a operator name.
        mutates_args ("unknown" | Iterable[str]): The arguments that are mutated in the function.

    Returns:
        The inferred schema.

    Example:
        >>> def foo_impl(x: torch.Tensor) -> torch.Tensor:
        >>>     return x.sin()
        >>>
        >>> infer_schema(foo_impl, op_name="foo", mutates_args={})
        foo(Tensor x) -> Tensor
        >>>
        >>> infer_schema(foo_impl, mutates_args={})
        (Tensor x) -> Tensor
    unknownNc                 (    t        d|  d d      )Nzinfer_schema(func): z Got func with signature ))
ValueError)whatsigs    K/home/dcms/DCMS/lib/python3.12/site-packages/torch/_library/infer_schema.pyerror_fnzinfer_schema.<locals>.error_fnD   s     /v5NseSTUVV    annotation_typec                 V    	 t        |       S # t        $ r  d|  d       Y y w xY w)NzUnsupported type annotation z. It is not a type.)eval	Exception)r   r   
pf_globals	pf_localss    r   convert_type_stringz)infer_schema.<locals>.convert_type_stringG   s<    	Y?? 	..??RS	s    ((tys.r   c                     g }d}| D ]#  } |      \  }}|j                  |       ||z  }% |rt        |      dfS | dfS )NFT)appendtuple)r   reschangedty
ty_changedunstringify_types        r   unstringify_typesz'infer_schema.<locals>.unstringify_typesO   s_      	"B-b1NB
JJrNz!G	" :t##:r   r%   c                     t        | t              r
 |       dfS t        j                  |       x}r. t        j                  |             \  }}|rt        ||      dfS | dfS )NTF)
isinstancestrtyping
get_originget_argsr   )r%   originargsargs_changedr   r(   s       r   r'   z&infer_schema.<locals>.unstringify_type]   sl     b#&r*D00((,,V,!26??23F!GD,#FD14775yr   Fz>We do not support positional-only args, varargs, or varkwargs.*Tz
Parameter z must have a type annotation.z

zFor example, z.

z has unsupported type z]. We do not support Tuple inputs in schema. As a workaround, please try to use List instead. zThe valid types are: .. The valid types are: zomutates_args must either be a sequence of the names of the arguments that are mutated or the string 'unknown'. r   zTensor(az!)zM is in mutable_args but only Tensors or collections of Tensors can be mutated "ztorch.z' has an unsupported default value type z;. Please file an issue on GitHub so we can prioritize this.=r   z in mutates_args were not found in the custom op's signature. mutates_args should contain the names of all args that the custom op mutates, or just the string 'unknown' if you don't know.(, z) -> )(__globals__inspect	signaturer+   r"   r   typeobjectr,   Anyboolset	enumerate
parametersitemssupported_paramkind	ParameterKEYWORD_ONLYr!   
annotationemptySUPPORTED_PARAM_TYPES
__origin__tuple_to_listkeysr   
startswithlenadddefaultr*   intfloattorchr   r   return_annotationparse_returnjoin)r   mutates_argsr   UNKNOWN_MUTATESparams	seen_argssaw_kwarg_only_argidxnameparamr   _	list_typeexample_type_strschema_typedefault_repr
dtype_repr	torch_dotmutates_args_not_seenrV   retr   r   r   r   r   r'   r(   s                        @@@@@@@r   infer_schemarj      s   T  O#//JI 

.
/CWS 5fs*+S01	uVZZ_%t+	,U4<#45 %

D@P:Q  FI'(<(<(>? FB]dEu%UV::**777%c"%)"w00666z$'DEF .e.>.>?"77))U2)/:	#)  5 : : <<)6yk'G$ &<U=M=M<N Or'(+,A,F,F,H+IL  &<U=M=M<N O,,A,F,F,H+IL
 ,O<$. O  %%h/ (RCMN0K/LM\!))(3 &st %SEKH,G+HIKd==G--333MM[M4&12L}}$
5==3tBT(U"5==1EMMC+>?!"5==/3EMM5;;7 /
$	!,,Y777)#i.*:; &MdSXS`S`NaMb cP Q MM[M4&,@AMFBN & #L 1I =$%)() *U V ,C,A,ABq
((
3C!DIIf-.eC599tyy !se,,r   	base_typecpp_type	list_baseoptional_base_listoptional_list_basec                 p   | ft         j                  |     dfg}dt        t        t         j                  f   fd}|r |j                  fd ||       D               |r1|j                  fd |t         j                  |          D               |r |j                  fd ||       D               |S )N?typc                     t         j                  |    t         j                  |    t        t        j
                  j                  | f      t        t        | f      fS N)r,   SequenceListr   collectionsabclist)rr   s    r   derived_seq_typesz(derived_types.<locals>.derived_seq_types   sF    OOC KK11C6:v&	
 	
r   c              3   ,   K   | ]  }| d f  yw)z[]N .0seq_typrl   s     r   	<genexpr>z derived_types.<locals>.<genexpr>   s!      
+2W
"o&
   c              3   ,   K   | ]  }| d f  yw)z?[]Nr|   r}   s     r   r   z derived_types.<locals>.<genexpr>   s%      
 
#&'
r   c              3   N   K   | ]  }t         j                  |    d f  yw)z[]?N)r,   r   r}   s     r   r   z derived_types.<locals>.<genexpr>   s.      
 __W%(3'78
s   "%)r,   r   r   r=   _SpecialFormextend)rk   rl   rm   rn   ro   resultrz   s    `     r   derived_typesr      s     
H		#z^4PF

uT6+>+>%>? 
  
6G	6R
 	
  
,V__Y-GH
 	
  
,Y7
 	
 Mr   c                     t         ddddft        ddddft        ddddft        ddddft        ddddft
        j                  ddddft        d	dddft        d
dddfg} g }| D ]  }|j                  t        |         t        |      S )Nr   TFSymIntrT   r@   r+   Scalar
ScalarTypeDevice)r   rS   rT   r@   r+   r	   Numberr   r   r   r   dict)datar   lines      r   get_supported_param_typesr      s     
4u-	heT*	ud+	vtUD)	eUE5)	xue4	eUE2	5%/
RD F ,mT*+,<r   r   zTensor[]r   rT   r@   r   c                    | y| t         j                  j                  u r |d       t        j                  |       }|t
        ur2| t        j                         vr |d|  dt         d       t        |    S t        j                  |       }|D ]  }|t        vs |d|  dt         d         ddj                  |D cg c]  }t        |    c}      z   dz   S c c}w )	Nz()z7No return type annotation was provided. Please add one.zReturn has unsupported type r4   r3   r8   r9   r   )
r;   rG   rJ   r,   r-   r"   SUPPORTED_RETURN_TYPESrN   r.   rX   )rI   r   r/   r0   args        r   rW   rW     s    W&&,,,JKz*FU388::.zl ;((>'?qB &j11??:&D ,,.zl ;((>'?qB 4HC237HIICOOHs   ?C
r`   c                     | j                   t        j                  j                  t        j                  j                  fv S rt   )rF   r;   rG   POSITIONAL_OR_KEYWORDrH   )r`   s    r   rE   rE   $  s6    :://&&  r   
tuple_typec                 .   t        | dd      }| t        j                  u s| t        u s|dk(  s|t        S t        |      dk(  rt        |d      S t        |      dk(  r|d   t        u rt        |d      S t        t        j                  t        |            S )z}
    Convert `tuple_type` into a list type with the same type arguments. Assumes that `tuple_type` is typing.Tuple type.
    __args__Nr|      r      )getattrr,   Tupler"   ry   rP   Ellipsisr   )r   	type_argss     r   rM   rM   +  s     
J5I 	fll"? 	Y1	IaL!!	Y1	1!9IaL!!FLLy!1233r   )"rw   r;   r,   r	   r   r   r   rU   r   r   r   torch.utils._exposed_inr
   _TestTensorCallabler+   rj   r=   r   r@   r   r   rv   ry   rS   rT   r   r   rW   rK   rG   rE   r"   rM   r|   r   r   <module>r      s?       "  . . .
 ll O "n-n-
 c]n- 	n- n-b"T6.../"" " 	"
 "J& H
KKL*	7&	LL( P6 23 7,,  4d5k 4d4j 4r   