
    Ǆg*                        d dl Z d dlZd dlmZmZ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d      dddej                  dee   d	efd
       Zd Zd Ze	dej                  e	   dededede
j*                  diZd Z e       Zde j2                  d	efdZdej6                  ej8                     d	ej6                  ej                     fdZy)    N)ListOptionalSequenceUnion)devicedtypeTensortypes)
exposed_inztorch.library)op_nameprototype_functionr   returnc                  d}t        j                  |       fddt        ffd}g }t               }d}t	        j
                  j                               D ]R  \  }\  }	}
t        |
      s d       |
j                  t         j                  j                  k(  r|s|j                  d       d}|
j                  t         j                  j                  u r d	|	 d
       |
j                  }t        |      t        k(  r ||      }|t        j!                         vr|j"                  t$        u r[t'        |      }d}|t        j!                         v rd| d} d	|	 d|
j                   d| dt        j!                          d	       n. d	|	 d|
j                   dt        j!                          d       t        |   }t        |      t        k(  r6||k7  rt)        d      |j+                  d      rJd| d|t-        d      d  }n5|	|v r1|j+                  d      s d	|	 d       d| d|t-        d      d  }|j/                  |	       |
j0                  t         j                  j                  u r|j                  | d|	        7d}|
j0                  %t3        |
j0                  t4        t6        t8        f      rt        |
j0                        }nt3        |
j0                  t        t:        j<                  f      rd|
j0                   d}nt3        |
j0                  t:        j>                        r9t        |
j0                        }d}|j+                  |      sJ |t-        |      d }n" d	|	 dt        |
j0                         d       |j                  | d|	 d|        U ||k7  r't        |      |z
  }t-        |      dkD  r | d        j@                  }t        |      t        k(  r ||      }tC        |      }|| d!d"jE                  |       d#| S d!d"jE                  |       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
    unknownc                 (    t        d|  d d      )Nzinfer_schema(func): z Got func with signature ))
ValueError)whatsigs    c/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/_library/infer_schema.pyerror_fnzinfer_schema.<locals>.error_fn9   s#    "4&(EcU!L
 	
    annotation_typec                 `    	 t        |       S # t        $ r} d|  d       Y d }~y d }~ww xY w)NzUnsupported type annotation z. It is not a type.)eval	Exception)r   er   s     r   convert_type_stringz)infer_schema.<locals>.convert_type_string>   s>    	(( 	..??RS 	s   
 	-(-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!)NzM 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) -> )#inspect	signaturestrset	enumerate
parametersitemssupported_paramkind	ParameterKEYWORD_ONLYappend
annotationemptytypeSUPPORTED_PARAM_TYPESkeys
__origin__tupletuple_to_listr   
startswithlenadddefault
isinstanceintfloatbooltorchr   r   return_annotationparse_returnjoin)r   mutates_argsr   UNKNOWN_MUTATESr   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_seenrD   retr   r   s                        @@r   infer_schemarW      sf   T  O


.
/C

S  FI'(<(<(>? HB]dEu%UV::**777%c"%)"w00666z$'DEF  ** C'1/BO"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&,@AQHBR & #L 1I =$%)() *U V --#%/0AB
((
3C!DIIf-.eC599tyy !se,,r   c                 f   | |ft         j                  |    | dfg}d }|r# ||       D ]  }|j                  || df        |r4 |t         j                  |          D ]  }|j                  || df        |r4 ||       D ])  }|j                  t         j                  |   | df       + |S )N?c                 N    t         j                  |    t         j                  |    gS N)typingr   r   )typs    r   derived_seq_typesz(derived_types.<locals>.derived_seq_types   s$    OOC KK
 	
r   z[]z?[]z[]?)r\   r   r2   )	base_typecpp_type	list_baseoptional_base_listoptional_list_baseresultr^   seq_typs           r   derived_typesrf      s     
H		#z^4F

 (3 	6GMM7xjO45	6()CD 	7GMM7xj$456	7(3 	HGMM6??73z5EFG	H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SymIntrA   rB   r)   Scalar
ScalarTypeDevice)r	   r@   rA   rB   r)   r
   Numberr   r   extendrf   dict)datard   lines      r   get_supported_param_typesrq      s     
4u-	heT*	ud+	vtUD)	eUE5)	xue4	eUE2	5%/
D F ,mT*+,<r   r	   zTensor[]rh   rA   rB   ri   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 r!   r    r%   r&   r   )
r'   r0   r4   r\   
get_originr9   SUPPORTED_RETURN_TYPESr7   get_argsrF   )r3   r   originargsargs        r   rE   rE      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
rN   c                     | j                   t        j                  j                  t        j                  j                  fv S r[   )r/   r'   r0   POSITIONAL_OR_KEYWORDr1   )rN   s    r   r.   r.      s6    :://&&  r   
tuple_typec                 n   t        | dd      }| t        j                  u s|dk(  s|t        j                  S t	        |      dk(  rt        j                  |d      S t	        |      dk(  r!|d   t
        u rt        j                  |d      S t        j                  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__N    r      )getattrr\   Tupler   r<   Ellipsisr   r9   )r{   	type_argss     r   r:   r:      s     
J5I V\\!Y"_	8I{{	Y1	{{9Q<((	Y1	1!9{{9Q<(({{6<<i(89::r   )r'   r\   r   r   r   r   rC   r   r   r	   r
   torch.utils._exposed_inr   Callabler)   rW   rf   rq   r@   rA   rB   rl   rt   rE   r6   r0   r.   Typer   r:   r~   r   r   <module>r      s      2 2  . . . O "T-T-
 c]T- 	T- T-n4& H
KK	7&	LL( P6 23 7,,  ;fkk&,,7 ;FKK<T ;r   