o
    j9:j7                     @   s,  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	ejd
edB defddZdeejB dedededef
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dej defd d!Z!d"ee" dee fd#d$Z#dS )%    N)GenericAlias)devicedtypeTensortypes)
exposed_in   )_resolve_opaque_type_infois_opaque_reference_typeis_opaque_typeztorch.library)op_nameprototype_functionr   returnc                  s  d}| j dt| fdddtffdd dttt tB d	f d
tttjd	f t	f ffdddtt tB d
ttjt	f f fddg }t
 }d}tj D ]m\}\}}	t|	skd |	jtjjkr{|s{|d d}|	jtjju rd| d |	j\}
}d}|
tvrt|
rt|
j}nT|
tjjkrd| d nEt|
dr|
jtu rt|
}d}|tv rd| d}d| d|	j d| dt  d	 nd| d|	j dt  d nt|
 }|du rt d | t|tu r&||krt!d!|"d"r%d#| d$|t#d"d  }n!||v rG|"d"s9d| d% d#| d$|t#d"d  }|$| |	j%tjju r_|| d&|  q\d}|	j%du sqt&|	j%t't(t	frwt|	j%}nFt&|	j%ttj)frd'|	j% d'}n4t&|	j%tj*rt|	j%}d(}|"|st d)|d*|t#|d }nd| d+t|	j% d, || d&| d-|  q\||krt
|| }t#|d.kr| d/ j+\}}t,|}|dur| d0d1-| d2| S d0d1-| d2| S )3aJ  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)Nzinfer_schema(func): z Got func with signature ))
ValueError)what)sig b/home/nk/hobo-godmode/plappi-mvp/.venv/lib/python3.10/site-packages/torch/_library/infer_schema.pyerror_fnI   s   zinfer_schema.<locals>.error_fnannotation_typec                    s4   zt | W S  ty    d|  d Y d S w )NzUnsupported type annotation z. It is not a type.)eval	Exception)r   )r   
pf_globals	pf_localsr   r   convert_type_stringL   s   

z)infer_schema.<locals>.convert_type_stringtys.r   c                    sH   g }d}| D ]} |\}}| | ||O }q|r t|dfS | dfS )NFT)appendtuple)r   reschangedty
ty_changed)unstringify_typer   r   unstringify_typesT   s   

z'infer_schema.<locals>.unstringify_typesr"   c                    sP   t | tr | dfS t|  }r$t| \}}|r$t||dfS | dfS )NTF)
isinstancestrtyping
get_originget_argsr   )r"   originargsargs_changed)r   r%   r   r   r$   b   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'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 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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.(, z) -> ).__globals__inspect	signaturer'   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hasattrr/   tuple_to_listkeysAssertionErrorr   
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_seenrW   retr   )r   r   r   r   r   r$   r%   r   infer_schema   s   *
*







 




rk   	base_typecpp_type	list_baseoptional_base_listoptional_list_basec                    s   |  ft j|    dfg}dtt jB fdd}|r(| fdd|| D  |r;| fdd|t j|  D  |rK| 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list)rr   r   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rm   r   r   	<genexpr>   s    
z derived_types.<locals>.<genexpr>c                 3   rz   )z?[]Nr   r{   r~   r   r   r      s
    
c                 3   s$    | ]}t j|   d fV  qdS )z[]?N)r(   Optionalr{   r~   r   r   r      s
    
)r(   r   r:   _SpecialFormextend)rl   rm   rn   ro   rp   resultry   r   r~   r   derived_types   s"   r   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} t	j
 rLddlm} | tt|ddddf g }| D ]	}|t|  qPt|S )Nr   TFSymIntrV   r=   r'   Scalar
ScalarTypeDevicer   )	GroupName)r   rU   rV   r=   r'   r   Numberr   r   rJ   distributedis_available"torch.distributed.distributed_c10dr   r   r(   castr:   r   r   dict)datar   r   liner   r   r   get_supported_param_types  s    
r   r   zTensor[]r   rV   r=   r   c                    s   | d u rdS | t jju r|d t| }|tur5| tvr1t| r&t| j	S |d|  dt d t|  S t
| }|D ]}|tvrQt|sQ|d|  dt d q<dd  d fd	d
|D }t|dkrnd| d }d| d S )Nz()z7No return type annotation was provided. Please add one.zReturn has unsupported type r1   r0   c                 S   s   t |  }r	|S t| jS rs   )SUPPORTED_RETURN_TYPESgetr	   rI   )argr"   r   r   r   _return_type_strC  s   
z&parse_return.<locals>._return_type_strr6   c                 3   s    | ]} |V  qd S rs   r   )r|   r   r   r   r   r   H  s    zparse_return.<locals>.<genexpr>r   r5   r   )r8   rD   rG   r(   r)   r   r   r
   r	   rI   r*   rY   rR   )rF   r   r+   r,   r   	output_tyr   r   r   rX   (  s:   


rX   ra   c                 C   s   | j tjjtjjfv S rs   )rC   r8   rD   POSITIONAL_OR_KEYWORDrE   )ra   r   r   r   rB   S  s   rB   
tuple_typec                 C   s   t | dd}| tju s| tu s|dks|du rtS t|dkr%t|d  S t|dkr7|d tu r7t|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   rx   rR   EllipsisUnion)r   	type_argsr   r   r   rN   Z  s   
rN   )$rv   r8   r(   r   r   rJ   r   r   r   torch.utils._exposed_inr   opaque_objectr	   r
   r   _TestTensorCallabler'   rk   r:   r   r=   r   r   ru   rx   rU   rV   r   r   rX   rH   rD   rB   r   rN   r   r   r   r   <module>   sV   	 G
'
(