
    9i5                        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 ddlmZ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j        diZd Z e            Z dej!        defdZ"dee#         dee         fdZ$dS )     N)GenericAlias)OptionalUnion)devicedtypeTensortypes)
exposed_in   )_OPAQUE_TYPESis_opaque_typeztorch.library)op_nameprototype_functionr   returnc               
   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                                                  D ]\  }\  }}	t          |	          s d           |	j        t          j        j        k    r|s|                    d           d}|	j        t          j        j        u r d| d            |	j                  \  }
}d}|
t,          vrt/          |
          rt0          |
         j        }n|
t4          j        j        k    r d| d           nt;          |
d          rc|
j        t          u rUt?          |
          }d}|t,          v rd| d} d| d|	j         d| dt,                                            d	           n? d| d|	j         dt,                                            d           nt,          |
         }|J t          |          t          u rH||k    rtC          d          |"                    d          rd| d|tG          d          d          }nE||v rA|"                    d          s d| d            d| d|tG          d          d          }|$                    |           |	j%        t          j        j        u r|                    | d!|            d}|	j%        'tM          |	j%        tN          tP          t          f          rt          |	j%                  }ntM          |	j%        t          t4          j)        f          rd"|	j%         d"}ntM          |	j%        t4          j*                  rEt          |	j%                  }d#}|"                    |          sJ |tG          |          d         }n$ d| d$t          |	j%                   d%           |                    | d!| d&|            ||k    r3t          |          |z
  }tG          |          d'k    r | d(            j+                  \  }}tY          |          }|| d)d*-                    |           d+| S d)d*-                    |           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                 0    t          d|  d d          )Nzinfer_schema(func): z Got func with signature ))
ValueError)whatsigs    N/var/www/icac/venv/lib/python3.11/site-packages/torch/_library/infer_schema.pyerror_fnzinfer_schema.<locals>.error_fnF   s%    UUUsUUUVVV    annotation_typec                 h    	 t          |           S # t          $ r  d|  d           Y d S 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_stringI   sf    	Y??? 	 	 	HSSSS     	s    11tys.r   c                     g }d}| D ]*} |          \  }}|                     |           ||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_typesQ   sp      	" 	"B--b11NB
JJrNNNz!GG 	::t##:r   r(   c                     t          | t                    r |           dfS t          j        |           x}r4 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_   s     b# 	8&&r**D00(,,,V 	8!2!26?23F3F!G!GD, 8#FD1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: 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_TYPESr   r   
class_nametorch_CScriptObjecthasattrr6   tuple_to_listkeysr   
startswithlenadddefaultr-   intfloatr   r   return_annotationparse_returnjoin)r   mutates_argsr   UNKNOWN_MUTATESparams	seen_argssaw_kwarg_only_argidxnameparamr   _schema_type	list_typeexample_type_strdefault_repr
dtype_repr	torch_dotmutates_args_not_seenr]   retr!   r   r   r    r   r*   r+   s                        @@@@@@@r   infer_schemarq      s   T  O#/JI 
.
/
/CW W W W WS        5fs*+S01	uVZ_%t+	,     U4<#45 %
D@P:Q        FI'(<(<(>(>?? WB WB]dEu%% 	WHUVVV:*777% *c"""%)"w0666HE$EEEFFF .-e.>??"777o.. +O<G EH$999Z Z Z Z    66#.%77)/::	#)  555'Gy'G'G'G$L L LU=M L L'L L -B,F,F,H,HL L L    L L LU=M L L,A,F,F,H,HL L L   
 0@K&&&$$.. O   %%h// ONNNCMMOO0LNN\!!))(33 tttt   KSJJKH,HJJKd=G-333MM[114112222L}$
5=3tBT(U(U$"5=11EMC+>?? 35=333EM5;77 	 //
$	!,,Y77777)#i..*:*:;Q Q QdSXS`NaNa Q Q Q  
 MM[@@4@@,@@AAAA&& #L 1 1I =$%%))H( V V V   ,+C,ABBq
((
3
3C99DIIf--99C999,tyy  ,,s,,,r   	base_typecpp_type	list_baseoptional_base_listoptional_list_basec                    | ft           j        |           dfg}dt          t          t           j        f         fd}|r*|                    fd ||           D                        |r:|                    fd |t           j        |                    D                        |r*|                    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)ry   s    r   derived_seq_typesz(derived_types.<locals>.derived_seq_types   sC    OC K1C6::v&&	
 	
r   c              3   &   K   | ]}| d fV  dS )z[]N .0seq_typrs   s     r   	<genexpr>z derived_types.<locals>.<genexpr>   s?       
 
+2Wooo&
 
 
 
 
 
r   c              3   &   K   | ]}| d fV  dS )z?[]Nr   r   s     r   r   z derived_types.<locals>.<genexpr>   sG       
 
  &&&'
 
 
 
 
 
r   c              3   F   K   | ]}t           j        |          d fV  dS )z[]?N)r/   r   r   s     r   r   z derived_types.<locals>.<genexpr>   sL       
 
 _W%('7'7'78
 
 
 
 
 
r   )r/   r   r   rA   _SpecialFormextend)rr   rs   rt   ru   rv   resultr   s    `     r   derived_typesr      sU    
H		#^^^4PF
uT6+>%>? 
 
 
 
  
 
 
 
 
6G6G	6R6R
 
 
 	
 	
 	
  
 
 
 
 
 -,V_Y-GHH
 
 
 	
 	
 	

  
 
 
 
 
,,Y7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
                                        r8ddlm} |                     t          j        t"          |          ddddf           g }| D ]}|                    t'          |            t)          |          S )Nr   TFSymIntr\   rD   r.   Scalar
ScalarTypeDevicer   )	GroupName)r   r[   r\   rD   r.   r	   Numberr   r   rQ   distributedis_available"torch.distributed.distributed_c10dr   r$   r/   castrA   r   r   dict)datar   r   lines       r   get_supported_param_typesr      s    
4u-	heT*	ud+	vtUD)	eUE5)	xue4	eUE2	5%/
RD %%'' P@@@@@@V[y115%NOOOF , ,mT*++++<<r   r   zTensor[]r   r\   rD   r   c                    | dS | t           j        j        u r |d           t          j        |           }|t
          ur-| t          vr |d|  dt           d           t          |          S t          j        |           }|D ]"}|t          vr |d|  dt           d           #d                    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 r8   r7   r=   c                 (    g | ]}t           |         S r   )SUPPORTED_RETURN_TYPES)r   args     r   
<listcomp>z parse_return.<locals>.<listcomp>:  s    GGG31#6GGGr   r   r<   r   )
r?   rK   rN   r/   r0   r%   r   r1   r_   rX   )rM   r   r2   r3   r   	output_tys         r   r^   r^   "  sX   tW&,,,JKKKz**FU333HBz B B(>B B B  
 &j11?:&&D  ,,,HBz B B(>B B B   		GG$GGGHHI 4yyA~~)Oc)	?S  r   rg   c                 T    | j         t          j        j        t          j        j        fv S r{   )rJ   r?   rK   POSITIONAL_OR_KEYWORDrL   )rg   s    r   rI   rI   E  s(    :/&  r   
tuple_typec                 z   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   r      )getattrr/   Tupler%   r   rX   Ellipsisr   )r   	type_argss     r   rU   rU   L  s     
J55I 	fl""?? 	Y1		IaL!!	Y1		1!9!9IaL!!FLy!1!1233r   )%r~   r?   r/   r	   r   r   r   rQ   r   r   r   torch.utils._exposed_inr
   opaque_objectr   r   _TestTensorCallabler.   rq   rA   r   rD   r   r   r}   r   r[   r\   r   r   r^   rO   rK   rI   r%   rU   r   r   r   <module>r      s&               " " " " " " " "  . . . . . . . . . . . . . . . . . . 8 8 8 8 8 8 8 8
 l O "- - --
 c]- 	- - - -D$T6../$$ $ 	$
 $ $ $ $N  4 H
KL*	7&	L( ! ! !@ 2133 7,     4d5k 4d4j 4 4 4 4 4 4r   