
    ^jG                        d dl Z d dlZd dlZd dlmZ d dlZd dlmZmZmZmZ d dl	m
Z
 ddlmZmZmZ ej                  Z e
d      ddd	d
ej                   dedz  dej$                  ej&                  ej$                     z  dz  defd       Zdeej,                  z  dedededef
dZd Zedej4                  e   dee   dedededej<                  diZd Z d Z! e       Z"dejF                  defdZ$d ee%   dee   fd!Z&y)"    N)GenericAlias)devicedtypeTensortypes)
exposed_in   )_resolve_opaque_type_infois_opaque_reference_typeis_opaque_typeztorch.library )op_nametagsprototype_functionr   r   returnc                  !"#$ d}| j                    d!t        j                  |       "|d}nt        |t        j
                        r|f}t        j
                  j                  |v }t        j
                  j                  |v }|r|rt        d      t        |      t        urt        |      }"fddt        f !fddt        t        t           t        z  d	f   d
t        t        t        j                  d	f   t        f   f#fd$dt        t           t        z  d
t        t        j                  t        f   f$fd#g }t!               }d}	d}
d}d}g }g }t#        "j$                  j'                               D ]<  \  }\  }}t)        |      s d       |j*                  t        j,                  j.                  k(  r|	s|j1                  d       d}	|j2                  t        j,                  j4                  u r d| d        #|j2                        \  }}d}|t6        vrt9        |      rt;        |      j<                  }n|t        j>                  j@                  k(  r d| d       ntC        |d      r_|jD                  t        u rMtG        |      }d}|t6        v rd| d} d| d|j2                   d| dt6        jI                          d	       n8 d| d|j2                   dt6        jI                          d       n	t6        |   }|t        d|       |j*                  t        j,                  jJ                  k(  r|
	|}
|}d| }d}t        |      t        u r8||k7  rtM        d       |jO                  d!      rNd}d"| d#|tQ        d!      d  }n7||v r3d}|jO                  d!      s d| d$       d"| d#|tQ        d!      d  }|rg|re|j*                  t        j,                  j.                  k7  r d%       |d"| d#k7  r d&       |j1                  d|        |j1                  |       |jS                  |       |jT                  t        j,                  j4                  u r|j1                  | d'|        d}|jT                  %t        |jT                  tV        tX        t        f      rt        |jT                        }nt        |jT                  t        t        jZ                  f      rd(|jT                   d(}nt        |jT                  t        j\                        rFt        |jT                        }d)}|jO                  |      st        d*|d+      |tQ        |      d }n" d| d,t        |jT                         d-       |j1                  | d'| d.|        ? ||k7  r't!        |      |z
  }tQ        |      d/kD  r | d0       |rC|
 d1       |d!k7  r d2       t        |      t        u st!        |      |
hk7  r d3| d       |rtQ        |      d/k(  r d4        #"j^                        \  }}|rta        |||      }ntc        |      }|r|d!k7  r d5       d6| d#}|| d7d8je                  |       d9| S d7d8je                  |       d9| S ):a,  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 an operator name.
        mutates_args ("unknown" | Iterable[str]): The arguments that are mutated in the function.
        tags (Tag | Sequence[Tag] | None): one or more tags to apply to the
            inferred schema. Use ``torch.Tag.inplace`` or ``torch.Tag.out`` to
            infer the conventional aliasing for those operator kinds.

    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
    unknownNr   z:torch.Tag.inplace and torch.Tag.out are mutually exclusivec                 (    t        d|  d d      )Nzinfer_schema(func): z Got func with signature ))
ValueError)whatsigs    f/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_library/infer_schema.pyerror_fnzinfer_schema.<locals>.error_fnY   s     /v5NseSTUVV    annotation_typec           
          	 t        |       S # t        $ r} d|  d| d       Y d }~y d }~wt        $ r/} d|  dt        |      j                   d| d       Y d }~y d }~ww xY w)NzUnsupported type annotation z. It is not a type. (z). If you are using 'from __future__ import annotations', note that annotations are evaluated lazily as strings; make sure all types referenced in annotations are importable at module scope, not only inside a local function.z: r   )eval	NameError	Exceptiontype__name__)r   er   
pf_globals	pf_localss     r   convert_type_stringz)infer_schema.<locals>.convert_type_string\   s    	Y?? 	..? @3 +,   	..? @G$$%Rs!- 	s    	A(-A(%A##A(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_typesn   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&   r0   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's type cannot be inferred from the schema as it is a ScriptObject. Please manually specify the schema using the `schema=` kwarg with the actual type of the ScriptObject.
__origin__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: zschema_type is None for param azomutates_args must either be a sequence of the names of the arguments that are mutated or the string 'unknown'. r   zTensor(a!)zM is in mutable_args but only Tensors or collections of Tensors can be mutatedz<torch.Tag.out requires mutable arguments to be keyword-only.zBtorch.Tag.out only supports mutable keyword-only Tensor arguments. "ztorch.zdtype repr z must start with '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.z8torch.Tag.inplace requires a positional Tensor argument.zHtorch.Tag.inplace requires the first positional argument to be a Tensor.z^torch.Tag.inplace requires mutates_args to contain exactly the first positional argument, got zItorch.Tag.out requires at least one mutable keyword-only Tensor argument.zDtorch.Tag.inplace requires the return annotation to be torch.Tensor.Tensor((, z) -> )3__globals__inspect	signaturer2   torchTaginplaceoutAssertionErrorr!   r3   r*   objectr4   Anyboolset	enumerate
parametersitemssupported_paramkind	ParameterKEYWORD_ONLYr)   
annotationemptySUPPORTED_PARAM_TYPESr   r
   
class_name_CScriptObjecthasattrr;   tuple_to_listkeysPOSITIONAL_OR_KEYWORDr   
startswithlenadddefaultintfloatr   r   return_annotation_infer_out_return_schemaparse_returnjoin)%r   mutates_argsr   r   UNKNOWN_MUTATES
is_inplaceis_outparams	seen_argssaw_kwarg_only_argfirst_positional_arg_name first_positional_arg_schema_typefirst_positional_arg_aliasout_arg_aliasesout_arg_namesidxnameparamr   _schema_type	list_typeexample_type_str
is_mutateddefault_repr
dtype_repr	torch_dotmutates_args_not_seenri   retr&   r   r$   r%   r   r/   r0   s%                                 @@@@@@@r   infer_schemar      s5   \  O#//JI 

.
/C|	D%))	$w""d*JYY]]d"FfH
 	
 L$\*WS $4<#%s*+	uVZZ_%t+	,T&\C/ E&**d:J4K  FI $'+$!%OM'(<(<(>? oB]dEu%UV::**777%c"%)"w00666z$'DEF .e.>.>?"77o.7HSS EHH$9$99  'Z Z 6#..%7)/:	#)  5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
 0@K #A$!HII JJ'++AAA)1(,%/:,+,SE&
$. O  %%h/!
 (RCMO0L/MN\!J))(3 &st %SEKH,H+IJKjzzW..;;;WXR00X ""Qse9-  &d==G--333MM[M4&12L}}$
5==3tBT(U"5==1EMMC+>?!"5==/3EMM5;;7 /
$	!,,Y7(%j^3LM   *#i.*:; &MdSXS`S`NaMb cP Q
 MM[M4&,@A_oB` & #L 1I =$%)() *U V $,OP+x7Z $L(9%>
 )
 66B^1F #o&!+W	
 ,C,A,ABq&x
 ,h7(?V 2326!DIIf-.eC599tyy !se,,r   	base_typecpp_type	list_baseoptional_base_listoptional_list_basec                 d   | ft         j                  |     dfg}dt        t         j                  z  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)r4   SequenceListr   collectionsabclist)r   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[]Nr   .0seq_typr   s     r   	<genexpr>z derived_types.<locals>.<genexpr>D  s!      
+2W
"o&
   c              3   ,   K   | ]  }| d f  yw)z?[]Nr   r   s     r   r   z derived_types.<locals>.<genexpr>H  s'      
  
#&'
r   c              3   N   K   | ]  }t         j                  |    d f  yw)z[]?N)r4   Optionalr   s     r   r   z derived_types.<locals>.<genexpr>N  s.      
 __W%(3'78
s   "%)r4   r   r!   _SpecialFormextend)r   r   r   r   r   resultr   s    `     r   derived_typesr   .  s     
H		#z^4KF
tf&9&99 
  
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} t        j                  j                         r4ddlm} | j                  t        j                   t"        |      ddddf       g }| D ]  }|j%                  t'        |         t)        |      S )Nr   TFSymIntrh   rP   r3   Scalar
ScalarTypeDevicer   )	GroupName)r   rg   rh   rP   r3   r   Numberr   r   rI   distributedis_available"torch.distributed.distributed_c10dr   r)   r4   castr!   r   r   dict)datar   r   lines       r   get_supported_param_typesr   U  s     
4u-	heT*	ud+	vtUD)	eUE5)	xue4	eUE2	5%/
LD %%'@V[[y15%NOF ,mT*+,<r   r   zTensor[]r   rh   rP   r   c                    | y| t         j                  j                  u r |d       t        j                  |       }|t
        urD| t        vr3t        |       rt        |       j                  S  |d|  dt         d       t        |    S t        j                  |       }|D ]*  }|t        vst        |      r |d|  dt         d       , d dj                  fd|D              }t        |      d	k(  rd
|z   dz   }d
|z   dz   S )Nz()z7No return type annotation was provided. Please add one.zReturn has unsupported type r=   r<   c                 ^    t         j                  |       x}r|S t        |       j                  S r   )SUPPORTED_RETURN_TYPESgetr
   r\   )argr-   s     r   _return_type_strz&parse_return.<locals>._return_type_str  s.    '++C0020I(-888r   rE   c              3   .   K   | ]  } |        y wr   r   )r   r   r   s     r   r   zparse_return.<locals>.<genexpr>  s     @C*3/@s   r	   rD   r   )rG   rW   rZ   r4   r5   r*   r   r   r
   r\   r6   rl   rd   )rY   r   r7   r8   r   	output_tyr   s         @r   rk   rk   x  s'   W&&,,,JKz*FU33'
30<GGG.zl ;((>'?qB
 &j11??:&D ,,5Mc5R.zl ;((>'?qB9
 		@4@@I 4yA~)Oc)	?S  r   c                 j   t        |      dk(  r	| t        u }nFt        j                  |       t        u xr) t        j
                  |       t        ft        |      z  k(  }|s |dt	        |       d       |D cg c]  }d| d
 }}t        |      dk(  r|d   S ddj                  |       d	S c c}w )
Nr	   z`torch.Tag.out requires the return annotation to match the mutable keyword-only Tensor arguments r<   rC   r?   r   rD   rE   r   )rd   r   r4   r5   r*   r6   rl   )ri   rw   rx   r   "return_annotation_matches_out_argsout_arg_aliasaliased_returnss          r   rj   rj     s     ?q ->&-H*-3->->.
. .
'89fYJ
 >
 
 	+ .55:=5I4J!M	

 IXX}r2XOX
?q q!!tyy)*!,, Ys   9B0r{   c                     | j                   t        j                  j                  t        j                  j                  fv S r   )rV   rG   rW   rb   rX   )r{   s    r   rU   rU     s6    :://&&  r   
tuple_typec                 4   t        j                  |       }| t         j                  u s
| t        u s|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.
    r	   r      )r4   r6   Tupler*   r   rd   EllipsisUnion)r   	type_argss     r   r`   r`     s     
+Ifll" 	Y1	IaL!!	Y1	1!9IaL!!FLLy!1233r   )'r   rG   r4   r   r   rI   r   r   r   torch.utils._exposed_inr   opaque_objectr
   r   r   _TestTensorCallabler3   rJ   r   r   r!   r   rP   r   r   r   r   rg   rh   r   r   rk   rj   r[   rW   rU   r*   r`   r   r   r   <module>r      so        . . .  ll O :<S-S-
 4ZS- ))fooeii0
04
7S- 	S- S-l$f)))$$ $ 	$
 $N2 H
KKL*	7&	LL( %!P-6 23 7,,  4d5k 4d4j 4r   