a
    h,1                     @   s  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ejee edd	d
Zeeejf eeeedddZdd Ze
deje
 dee
 dedededejdiZdd Ze ZejedddZee  ee dddZ!dS )    N)GenericAlias)OptionalUnion)devicedtypeTensortypes)
exposed_inztorch.library)op_name)prototype_functionr
   returnc                  s  d}| j dt| fddtdfdd tttt tf df tttj	df t
f d	fd
dttt tf ttj	t
f d fd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\}
}|
tvr|
jtu rt|
}d}|t v rdd| d}d| d|	j d| dt  d	 n"d| d|	j dt  d t|
 }t|tkr||krtd|drDd| d |tdd  }nB||v rD|ds(d| d! d| d |tdd  }|| |	jtjju rt|| d"|  qd}|	jdu st|	jt t!t
frt|	j}nt|	jtt"j#frd#|	j d#}n\t|	jt"j$rt|	j}d$}||sJ |t|d }nd| d%t|	j d& || d"| d'|  q||krrt|| }t|d(krr| d) j%\}}t&|}|dur| 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                    s   t d|  d  dd S )Nzinfer_schema(func): z Got func with signature ))
ValueError)what)sig I/var/www/auris/lib/python3.9/site-packages/torch/_library/infer_schema.pyerror_fnD   s    zinfer_schema.<locals>.error_fnannotation_typec                    s6   zt | W S  ty0    d|  d Y n0 d S )NzUnsupported type annotation z. It is not a type.)eval	Exceptionr   )r   
pf_globals	pf_localsr   r   convert_type_stringG   s    
z)infer_schema.<locals>.convert_type_string.)tysr   c                    sL   g }d}| D ]"} |\}}| | ||O }q|r@t|dfS | dfS d S )NFT)appendtuple)r   reschangedtyZ
ty_changed)unstringify_typer   r   unstringify_typesO   s    

z'infer_schema.<locals>.unstringify_types)r!   r   c                    sP   t | tr | dfS t|  }rHt| \}}|rHt||dfS | dfS )NTF)
isinstancestrtyping
get_originget_argsr   )r!   originargsZargs_changed)r   r#   r   r   r"   ]   s    
z&infer_schema.<locals>.unstringify_typeFz>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   Zmutates_argsr
   ZUNKNOWN_MUTATESparamsZ	seen_argsZsaw_kwarg_only_argidxnameparamr   _Z	list_typeZexample_type_strZschema_typeZdefault_reprZ
dtype_reprZ	torch_dotZmutates_args_not_seenrO   retr   )r   r   r   r   r   r"   r#   r   infer_schema   s    *
	,





 



rX   )	base_typecpp_type	list_baseoptional_base_listoptional_list_basec                    s   |  ft j|    dfg}ttt jf ddd}|rT| fdd|| D  |rz| fdd|t j|  D  |r| fdd|| D  |S )	N?typc                 S   s,   t j|  t j|  ttjj| ftt| ffS N)r&   SequenceListr   collectionsabclistr_   r   r   r   derived_seq_types   s
    
z(derived_types.<locals>.derived_seq_typesc                 3   s   | ]}|  d fV  qdS )z[]Nr   .0Zseq_typrZ   r   r   	<genexpr>   s   z derived_types.<locals>.<genexpr>c                 3   s   | ]}|  d fV  qdS )z?[]Nr   rh   rj   r   r   rk      s   c                 3   s"   | ]}t j|   d fV  qdS )z[]?N)r&   r   rh   rj   r   r   rk      s   )r&   r   r   r6   _SpecialFormextend)rY   rZ   r[   r\   r]   resultrg   r   rj   r   derived_types   s"    ro   c                  C   s   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 ]}|	t
|  qnt|S )Nr   TFSymIntrM   r9   r%   ScalarZ
ScalarTypeZDevice)r   rL   rM   r9   r%   r   Numberr   r   rm   ro   dict)datarn   liner   r   r   get_supported_param_types   s    rv   r   zTensor[]rp   rM   r9   rq   c                 C   s   | d u rdS | t jju r |d t| }|tur\| t vrT|d|  dt d t|  S t| }|D ]"}|tvrj|d|  dt d qjd	dd |D }t
|d	krd
| d }d
| d S )Nz()z7No return type annotation was provided. Please add one.zReturn has unsupported type r-   r,   r2   c                 S   s   g | ]}t | qS r   )SUPPORTED_RETURN_TYPES)ri   argr   r   r   
<listcomp>      z parse_return.<locals>.<listcomp>   r1   r   )r4   r@   rC   r&   r'   r   rw   rG   r(   rQ   rI   )rB   r   r)   r*   rx   Z	output_tyr   r   r   rP     s2    

rP   )rU   r   c                 C   s   | j tjjtjjfv S ra   )r?   r4   r@   POSITIONAL_OR_KEYWORDrA   )rU   r   r   r   r>   (  s    r>   )
tuple_typer   c                 C   s   t | dd}| tju s.| tu s.|dks.|du r2tS t|dkrJt|d  S t|dkrn|d tu rnt|d  S ttjt|  S d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   rf   rI   Ellipsisr   )r}   Z	type_argsr   r   r   rF   /  s    rF   )"rd   r4   r&   r   r   r   r   rN   r   r   r   Ztorch.utils._exposed_inr	   Z_TestTensorCallabler%   rX   r6   rl   r9   ro   rv   rc   rf   rL   rM   rr   rw   rP   rD   r@   r>   r   rF   r   r   r   r   <module>   sF    3%
