o
    ߗiA*                     @   s   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
dZdd Zdd Ze	deje	 dededede
jdiZdd Ze Zde jd	efddZdejej d	ejej fddZdS )    N)ListOptionalSequenceUnion)devicedtypeTensortypes)
exposed_inztorch.library)op_nameprototype_functionr   returnc                  sZ  d}t | fdd dtf fdd}g }t }d}tj D ]>\}\}	}
t|
s3 d |
jt j	j
krC|sC|d	 d
}|
jt j	ju rR d|	 d |
j}t|tkr_||}|t vr|jtu rt|}d}|t v r|d| d} d|	 d|
j d| dt  d	 n d|	 d|
j dt  d t| }t|tkr||krtd|drd| d|tdd  }n|	|v r|dsو d|	 d d| d|tdd  }||	 |
jt j	ju r|| d|	  q$d}|
jdu st|
jtttfrt|
j}n@t|
jttjfr(d|
j d}n.t|
jtjrHt|
j}d}||s?J |t|d }n d|	 dt|
j d || d|	 d |  q$||kr}t|| }t|d!kr} | d" j }t|tkr||}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
    unknownc                    s   t d|  d  d)Nzinfer_schema(func): z Got func with signature ))
ValueError)what)sig Y/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/torch/_library/infer_schema.pyerror_fn9   s   zinfer_schema.<locals>.error_fnannotation_typec              
      sB   zt | W S  ty  } z d|  d W Y d }~d S d }~ww )NzUnsupported type annotation z. It is not a type.)eval	Exception)r   e)r   r   r   convert_type_string>   s   

z)infer_schema.<locals>.convert_type_stringFz>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_seenr@   retr   )r   r   r   infer_schema   s   *






 



rS   c                    s   |  ft j|    dfg}dd }|r"| fdd|| D  |r5| fdd|t j|  D  |rE| fdd|| D  |S )N?c                 S   s   t j|  t j|  gS N)typingr   r   )typr   r   r   derived_seq_types   s   z(derived_types.<locals>.derived_seq_typesc                 3       | ]
}|  d fV  qdS )z[]Nr   .0seq_typcpp_typer   r   	<genexpr>   s    
z derived_types.<locals>.<genexpr>c                 3   rY   )z?[]Nr   rZ   r]   r   r   r_      s
    
c                 3   s$    | ]}t j|   d fV  qdS )z[]?N)rV   r   rZ   r]   r   r   r_      s
    
)rV   r   extend)	base_typer^   	list_baseoptional_base_listoptional_list_baseresultrX   r   r]   r   derived_types   s"   rf   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
|  q7t|S )Nr   TFSymIntr=   r>   r%   Scalar
ScalarTypeDevice)r   r<   r=   r>   r%   r	   Numberr   r   r`   rf   dict)datare   liner   r   r   get_supported_param_types   s   ro   r   zTensor[]rg   r=   r>   rh   c                 C   s   | d u rdS | t jju r|d t| }|tur.| t vr*|d|  dt d t|  S t| }|D ]}|tvrF|d|  dt d q5dd	dd	 |D  d
 S )Nz()z7No return type annotation was provided. Please add one.zReturn has unsupported type r   r   r!   r"   c                 S   s   g | ]}t | qS r   )SUPPORTED_RETURN_TYPES)r[   argr   r   r   
<listcomp>   s    z parse_return.<locals>.<listcomp>r   )
r#   r,   r0   rV   
get_originr5   rp   r3   get_argsrB   )r/   r   originargsrq   r   r   r   rA      s.   

rA   rJ   c                 C   s   | j tjjtjjfv S rU   )r+   r#   r,   POSITIONAL_OR_KEYWORDr-   )rJ   r   r   r   r*      s   r*   
tuple_typec                 C   s   t | dd}| tju s|dks|du rtjS t|dkr#tj|d  S t|dkr6|d tu r6t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__Nr      r      )getattrrV   Tupler   r8   Ellipsisr   r5   )rx   	type_argsr   r   r   r6     s   r6   )r#   rV   r   r   r   r   r?   r   r   r   r	   torch.utils._exposed_inr
   Callabler%   rS   rf   ro   r<   r=   r>   rk   rp   rA   r2   r,   r*   Typer}   r6   r   r   r   r   <module>   s:    

&