a
    h^U                     @   s  U d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZ d dlZd dlmZ d dlmZmZ ddlmZ erddlmZ g dZed	d
G dd de	Zi Zeeeej f ed< dd Ze eej< G dd dZej ej!ej"ej#ej$j%e j&ej'e e(dej)e*ddZ+e,eD ]Z-e.ee-e+e-< q2dedddZ/ej0j1ejdddZ2i Z3ee4e5e5f ejf ed< ej0j1ejdddZ6ed	d
ee4d ee5df d d!d"Z7ed	d
d5ee8d#d$d%Z9ed	d
d&d' Z:ed	d
eed(d)d*Z;ed	d
d6ee4ed+f e
ee5ef  e
e4e  e
ee5ef  e8e
e d,d-d.Z<ed	d
d7ej=j>e5e4e e
ee5ef  e8e
e d/d0d1Z?eje4ed+f ee5ef e8e
e d2d3d4Z@dS )8    N)AnyCallablecast
NamedTupleOptionalTYPE_CHECKING)boolean_dispatched)
OpOverloadOpOverloadPacket   )compatibility)Argument)ArgsKwargsPaircheck_for_mutable_operationget_signature_for_torch_opcreate_type_hinttype_matchesnormalize_functionnormalize_moduleF)Zis_backward_compatiblec                   @   s2   e Zd ZU dZeedf ed< eeef ed< dS )r   z<
    Simple named tuple for wrapping args/kwargs pairs.
    .argskwargsN)	__name__
__module____qualname____doc__tupler   __annotations__dictstr r   r   G/var/www/auris/lib/python3.9/site-packages/torch/fx/operator_schemas.pyr      s   
r   _manual_overridesc                  C   s>   g } dd }|  t| tddd}|  t| | S )Nc                 S   s   d S Nr   )selfr   r   r    nonzero/   s    z!_nonzero_schemas.<locals>.nonzero)as_tuplec                S   s   d S r"   r   )r#   r%   r   r   r    r$   4   s    )appendinspect	signaturebool)
signaturesr$   r   r   r    _nonzero_schemas,   s    r+   c                   @   s   e Zd Zdd ZdS )_FakeGlobalNamespacec                 C   s   |dkrt S tdd S )Ntorchz!Expected a torch namespace lookup)r-   RuntimeError)r#   namer   r   r    __getattr__@   s    z _FakeGlobalNamespace.__getattr__N)r   r   r   r0   r   r   r   r    r,   ?   s   r,   t)TensorZDeviceZLayoutnumberFutureZAnyEnumTypeZQSchemeZ	__torch__ZNoneTypeZStorager1   ztorch._C.JitType)ts_typereturnc                 C   s   t | jtS )z
    Convert a TorchScript type to a Python type (including subtypes) via
    eval'ing the annotation_str. _type_eval_globals sets up expressions
    like "List" and "Future" to map to actual types (typing.List and jit.Future)
    )evalZannotation_str_type_eval_globals)r5   r   r   r     _torchscript_type_to_python_typeW   s    r9   )	ts_schemar6   c              	   C   s   ddl m} g }| jD ]}t|j}| r2|jn|j}|jdkrH|jnd}|j	rX|j
n|j}|dkr||jkstJ |j}t|D ]4\}}	|	j|jksJ ||	j|j|	j|	jd||< q||||||d qdd | jD }
t|
dkrd }n t|
d	kr
|
d }nt|
}t j||d
S )Nr   )	Parameterr#   inputfrom)r/   kinddefault
annotationc                 S   s   g | ]}t |jqS r   )r9   type).0retr   r   r    
<listcomp>   s   z9_torchscript_schema_to_signature_impl.<locals>.<listcomp>r   )return_annotation)r'   r;   	argumentsr9   rA   Zhas_default_valuedefault_valueemptyr/   Z
kwarg_onlyKEYWORD_ONLYPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLY	enumerater>   r?   r@   r&   returnslenr   	Signature)r:   r;   
parametersargarg_typer?   r/   r>   idxpZreturn_typesreturn_typer   r   r    %_torchscript_schema_to_signature_impl`   sB    


rV   _SCHEMA_TO_SIGNATURE_CACHEc                 C   s6   | j | jf}t|}|d ur"|S t| }|t|< |S r"   )r/   Zoverload_namerW   getrV   )r:   	cache_keyZ	cache_valresr   r   r     _torchscript_schema_to_signature   s    
r[   )r   .r   )targetr   r   c              	   C   s   t | dd\}}|r|rg }t||D ]B\}}z"|j|i | |||f W q& tyf   Y q&Y q&0 q&dd }t|dkrn"t|dkr|d \}	}
||
 n d S )NT)return_schemasc                 S   s   | j rtd|  dd S )Nz!Tried to trace mutable operation z|. FX only supports functional code, so operations that mutate operands in-place (e.g. via `out` arguments) are not supported)Z
is_mutabler.   )schemar   r   r    throw_if_mutable   s    
z5check_for_mutable_operation.<locals>.throw_if_mutabler   r   )r   zipbindr&   	TypeErrorrN   )r\   r   r   r*   schemasmatched_schemascandidate_signaturer^   r_   _Zschema_to_checkr   r   r    r      s     
r   )opr]   c                    s   t  tr jg}nnt  tr6 fdd  D }nLt }|rT|rP|dfS dS tjj	
 }|du rv|rrdS dS tj|}dd |D }|r||fS |S )a  
    Given an operator on the `torch` namespace, return a list of `inspect.Signature`
    objects corresponding to the overloads of that op.. May return `None` if a signature
    could not be retrieved.

    Args:
        op (Callable): An operator on the `torch` namespace to look up a signature for

    Returns:
        Optional[List[inspect.Signature]]: A list of signatures for the overloads of this
            operator, or None if the operator signatures could not be retrieved. If
            return_schemas=True, returns a tuple containing the optional Python signatures
            and the optional TorchScript Function signature
    c                    s   g | ]}t  |jqS r   )getattr_schema)rB   overloadrg   r   r    rD          z.get_signature_for_torch_op.<locals>.<listcomp>N)NNc                 S   s   g | ]}t |qS r   )r[   rB   r^   r   r   r    rD      rl   )
isinstancer	   ri   r
   Z	overloadsr!   rX   r-   jitZ	_builtinsZ_find_builtin_CZ_jit_get_schemas_for_operator)rg   r]   rc   overrideZaten_fnr*   r   rk   r    r      s    



r   c                 C   s   zt | ttfrt | tr$dd }ndd }t| dkrB|tW S | d }| D ]0}t||r`qNqNt||rp|}qN|t  W S qN||W S W n" ty   td|   Y n0 | S )a  
    Produces a type hint for the given argument.

    The :func:`create_type_hint` looks for a type hint compatible with the input argument `x`.

    If `x` is a `list` or `tuple`, it looks for an object in the list whose type is a superclass
    of the rest, and uses that as `base_type` for the `List` or `Tuple` to be returned.
    If no such object is found, it defaults to `List[Any]`.

    If `x` is neither a `list` nor a `tuple`, it returns `x`.
    c                 S   s   t |  S r"   )listxr   r   r    ret_type  s    z"create_type_hint.<locals>.ret_typec                 S   s   t | df S )N.)r   rs   r   r   r    ru     s    r   z@We were not able to successfully create type hint from the type )	rn   rr   r   rN   r   
issubclass	Exceptionwarningswarn)rt   ru   Z	base_typer1   r   r   r    r      s(    





r   )signature_typeargument_typec                    s  t | d| }|  u rdS |tju rF|  krF| j}t fdd|D S t | dd tu r| jd  tu rttu rtdS tst	
d|  d dS t  dd tu rt jd S fd	d
}| S | tu rވ tju rdS | tju r tthv rdS t rt| rt | S dS )N
__origin__Tc                 3   s   | ]}t | V  qd S r"   )r   rB   c)r{   r   r    	<genexpr>'  rl   ztype_matches.<locals>.<genexpr>r   z.Does not support nested parametric types, got z. Please file a bug.Fc                    s>   t | dd turdS | j}| jdkr(dS t fdd|D S )Nr|   F)r   Tc                 3   s    | ]}|t u pt| V  qd S r"   )Ellipsisrv   r}   sig_el_typer   r    r   >  rl   z=type_matches.<locals>.is_homogeneous_tuple.<locals>.<genexpr>)rh   r   __args__all)r1   Z	containedr   r   r    is_homogeneous_tuple8  s    
z*type_matches.<locals>.is_homogeneous_tuple)rh   typingUnionr   anyrr   intr'   isclassrx   ry   rv   r-   ZdtypenumbersNumberfloat)rz   r{   Zsig_origin_typeZsig_containedr   r   )r{   r   r    r     s4    


	
r   .)r\   r   r   	arg_typeskwarg_typesnormalize_to_only_use_kwargsr6   c              	   C   sb  |du ri }d}t | tjs:t | ttfs:t| dr:| j} t | tjst | ttfs| }| tv rt | trnJ t|  }|d |d  }	}
t	
|	jt	
|
jkrdS |	}t|sJ t	
t	|}t||||}nt| sJ t| }g }|r^|D ]<}z|j|i | || W q ty2   Y qY q0 qt|dkrHnt|dkrjt|d |||}n|dus~|dur0|r|nttt d}|r|ni }|D ]}d}zF|j|i |}|j D ]&\}}|j| }|ot|j|}qW n ty   d	}Y n0 |rt||||} q^qn.d
dd |D }tdt|  d| |S )a  
    Returns normalized arguments to PyTorch functions. This means that
    `args/kwargs` will be matched up to the functional's
    signature and return exclusively kwargs in positional order if
    `normalize_to_only_use_kwargs` is True.
    Also populates default values. Does not support positional-only
    parameters or varargs parameters (*args, **kwargs). Does not support modules.

    May require `arg_types` and `kwarg_types` in order to disambiguate overloads.

    Args:
        target (Callable): Function that we are normalizing
        args (Tuple[Any]): Tuple of args to the function
        kwargs (Optional[Dict[str, Any]]): Dict of kwargs to the function
        arg_types (Optional[Tuple[Any]]): Tuple of arg types for the args
        kwarg_types (Optional[Dict[str, Any]]): Dict of arg types for the kwargs
        normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.

    Returns:

        Returns normalized_args_and_kwargs, or `None` if not successful.
    N_opif_trueif_falser   r   r   TF
c                 s   s   | ]}t |V  qd S r"   )r   rm   r   r   r    r     s   z%normalize_function.<locals>.<genexpr>z Tried to normalize arguments to zy but the schema match was ambiguous! Please provide argument types to the normalize_arguments() call. Available schemas:
)rn   typesBuiltinFunctionTyper
   r	   hasattrr   r   r   r'   r(   rP   callableunwrap&_args_kwargs_to_normalized_args_kwargsr   ra   r&   rb   rN   r   r   r   rF   itemsr   r@   joinr.   r-   typename)r\   r   r   r   r   r   new_args_and_kwargsZtarget_for_analysisZ
dispatchedr   r   sigZtorch_op_schemasrd   re   Zsig_matchesZbound_typesZarg_namerR   paramZschema_printoutsr   r   r    r   O  s    
	




r   )rootr\   r   r   r   r6   c           
   
   C   s   z|  |}W n6 tyD } ztd| d|W Y d}~n
d}~0 0 t|jdr|jj}ttj|d|jkrt	
t	|j}|du ri }t||||}	|	S dS )a(  
    Returns normalized arguments to PyTorch modules. This means that
    `args/kwargs` will be matched up to the functional's
    signature and return exclusively kwargs in positional order if
    `normalize_to_only_use_kwargs` is True.
    Also populates default values. Does not support positional-only
    parameters or varargs parameters (*args, **kwargs).

    Args:
        root (nn.Module): root module upon which we query modules
        target (Callable): Function that we are normalizing
        args (Tuple[Any]): Tuple of args to the function
        kwargs (Optional[Dict[str, Any]]): Dict of kwargs to the function
        normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.

    Returns:

        Returns normalized_args_and_kwargs, or `None` if not successful.
    z$Tried to normalize node with target z# but root did not have that target!Nr   )Zget_submoduleAttributeErrorr.   r   	__class__r   rh   r-   nnr'   r(   r   Zforwardr   )
r   r\   r   r   r   Zsubmode	classnamer   r   r   r   r    r     s&    
r   )r   r   r   r   r6   c           	         s   t jjt jjh t fdd| j D rFt| j g dkrFdS | j	|i |}|
  i }g }t| jD ]8\}}|s|t|k r||j|  qp|j| ||< qptt||S )a  
    Given a call target, args, and kwargs, return the arguments normalized into
    an ArgsKwargsPair, or None if the type signature is not supported by
    this normalization.

    Args:

        sig (inspect.Signature): Signature object for the target
        args (Tuple): Arguments that appear at the callsite for `target`
        kwargs (Dict): Keyword arguments that appear at the callsite for `target`
        normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.

    Returns:

        Optional[ArgsKwargsPair]: Normalized args and kwargs for `target`, or `None` if
            this target is not supported.
    c                 3   s   | ]}|j  vV  qd S r"   )r>   )rB   rT   Zsupported_parameter_typesr   r    r   #  rl   z9_args_kwargs_to_normalized_args_kwargs.<locals>.<genexpr>)r<   r=   to	generatorN)r'   r;   rJ   rI   r   rP   valuesrr   keysra   apply_defaultsrL   rN   r&   rF   r   r   )	r   r   r   r   Z
bound_argsZ
new_kwargsnew_argsir   r   r   r    r     s    r   )F)NNNF)NF)Aenumr'   r   r   r   rx   r   r   r   r   r   r   r-   Ztorch._jit_internalr   Z
torch._opsr	   r
   Z_compatibilityr   noder   __all__r   r!   r   rr   rO   r   r+   r$   r,   r2   ZdeviceZlayoutr   ro   r4   EnumZqschemerA   ZUntypedStorageTypeVarr8   dirkrh   r9   rp   ZFunctionSchemarV   rW   r   r   r[   r   r)   r   r   r   r   r   Moduler   r   r   r   r   r    <module>   s   
 	
3'"
,2    

   /

