o
    ߗihS                     @   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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rOd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.< qdddefddZ0dej1j2dejfddZ3i Z4e	ee5e5f ejf ed< dej1j2dejfddZ6ed	d
ded ed! d"e	e5d#f fd$d%Z7ed	d
d<d&ed'e8fd(d)Z9ed	d
d*d+ Z:ed	d
d,ed-efd.d/Z;ed	d
					d=ded ee d"ee	e5ef  d0eee  d1ee	e5ef  d2e8dee fd3d4Z<ed	d
			d>d5ej=j>de5d ee d"ee	e5ef  d2e8dee fd6d7Z?d8ejd eed9f d"e	e5ef d2e8dee f
d:d;Z@dS )?    N)	AnyCallablecastDictList
NamedTupleOptionalTuple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)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__r	   r   __annotations__r   str r!   r!   W/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/torch/fx/operator_schemas.pyr   )   s   
 r   _manual_overridesc                  C   s>   g } dd }|  t| dtfdd}|  t| | S )Nc                 S      d S Nr!   )selfr!   r!   r"   nonzero9      z!_nonzero_schemas.<locals>.nonzeroas_tuplec                S   r$   r%   r!   )r&   r)   r!   r!   r"   r'   >   r(   )appendinspect	signaturebool)
signaturesr'   r!   r!   r"   _nonzero_schemas6   s   r/   c                   @   s   e Zd Zdd ZdS )_FakeGlobalNamespacec                 C   s   |dkrt S td)Ntorchz!Expected a torch namespace lookup)r1   RuntimeError)r&   namer!   r!   r"   __getattr__J   s   z _FakeGlobalNamespace.__getattr__N)r   r   r   r4   r!   r!   r!   r"   r0   I   s    r0   t)TensorDeviceLayoutnumberFutureAnyEnumTypeQScheme	__torch__NoneTypeStorager5   ts_typeztorch._C.JitType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)
    )evalannotation_str_type_eval_globals)r@   r!   r!   r"    _torchscript_type_to_python_typea   s   rE   	ts_schemac              	   C   s  ddl m} g }| jD ]\}t|j}| r|jn|j}|jdkr$|jnd}|j	r,|j
n|j}|dkr\||jks:J |j}t|D ]\}}	|	j|jksMJ ||	j|j|	j|	jd||< qA||||||d qdd | jD }
t|
dkryd }nt|
d	kr|
d }nt|
}t j||d
S )Nr   )	Parameterr&   inputfrom)r3   kinddefault
annotationc                 S   s   g | ]}t |jqS r!   )rE   type).0retr!   r!   r"   
<listcomp>   s    
z9_torchscript_schema_to_signature_impl.<locals>.<listcomp>r   )return_annotation)r+   rG   	argumentsrE   rM   has_default_valuedefault_valueemptyr3   
kwarg_onlyKEYWORD_ONLYPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLY	enumeraterJ   rK   rL   r*   returnslentuple	Signature)rF   rG   
parametersargarg_typerK   r3   rJ   idxpreturn_typesreturn_typer!   r!   r"   %_torchscript_schema_to_signature_implj   sB   


rf   _SCHEMA_TO_SIGNATURE_CACHEc                 C   s6   | j | jf}t|}|d ur|S t| }|t|< |S r%   )r3   overload_namerg   getrf   )rF   	cache_key	cache_valresr!   r!   r"    _torchscript_schema_to_signature   s   
rm   targetr   )r   .r   r   c              	   C   s   t | dd\}}|rS|rUg }t||D ]\}}z|j|i | |||f W q ty1   Y qw dd }t|dkr>d S t|dkrP|d \}	}
||
 d S 	 d S d S 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)
is_mutabler2   )schemar!   r!   r"   throw_if_mutable   s
   
z5check_for_mutable_operation.<locals>.throw_if_mutabler   r   )r   zipbindr*   	TypeErrorr\   )rn   r   r   r.   schemasmatched_schemascandidate_signaturerq   rr   _schema_to_checkr!   r!   r"   r      s$   r   opro   c                    s   t  tr
 jg}n7t  tr fdd  D }n&t }|r*|r(|dfS dS tjj	
 }|du r;|r9dS dS tj|}dd |D }|rN||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)rN   overloadr{   r!   r"   rP      s    z.get_signature_for_torch_op.<locals>.<listcomp>N)NNc                 S   s   g | ]}t |qS r!   )rm   rN   rq   r!   r!   r"   rP      s    )
isinstancer   r}   r   	overloadsr#   ri   r1   jit	_builtins_find_builtin_C_jit_get_schemas_for_operator)r{   ro   rv   overrideaten_fnr.   r!   r   r"   r      s   



r   c                 C   s   zEt | ttfrCt | trdd }ndd }t| dkr!|tW S | d }| D ]}t||r/q't||r7|}q'|t  W S ||W S W | S  tyW   td|   Y | S w )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%   )r   xr!   r!   r"   ret_type  s   z"create_type_hint.<locals>.ret_typec                 S   s   t | df S )N.)r	   r   r!   r!   r"   r     s   r   z@We were not able to successfully create type hint from the type )	r   listr]   r\   r   
issubclass	Exceptionwarningswarn)r   r   	base_typer5   r!   r!   r"   r      s.   





r   signature_typeargument_typec                    s&  t | d| }|  u rdS |tju r#|  kr#| j}t fdd|D S | tt u r/ tu r/dS t | dd tthv rj| jd t	sNt
d|  d dS t  dd tthv r`t jd S fd	d
}| S | tu ru tju rudS | tju r tthv rdS t	 rt	| rt | S dS )N
__origin__Tc                 3   s    | ]}t | V  qd S r%   )r   rN   c)r   r!   r"   	<genexpr>1      ztype_matches.<locals>.<genexpr>r   z.Does not support nested parametric types, got z. Please file a bug.Fc                    sB   t | dd tthv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%   )Ellipsisr   r   sig_el_typer!   r"   r   G  s     z=type_matches.<locals>.is_homogeneous_tuple.<locals>.<genexpr>)r|   r]   r	   __args__all)r5   	containedr   r!   r"   is_homogeneous_tupleA  s   
z*type_matches.<locals>.is_homogeneous_tuple)r|   typingUnionr   anyr   intr   r+   isclassr   r   r   r1   dtypenumbersNumberfloat)r   r   sig_origin_typesig_containedr   r!   )r   r   r"   r   &  s4   


	
r   	arg_typeskwarg_typesnormalize_to_only_use_kwargsc              	   C   s   |du ri }d}t | tjsVt | ttfsV| }| tv r?t | tr"J t|  }|d |d }	}
t|	j	t|
j	kr=dS |	}t
|sEJ tt|}t||||}|S t
| s\J t| }g }|r|D ]}z|j|i | || W qg ty   Y qgw t|dkr	 |S t|dkrt|d |||}|S |dus|dur|r|nttt d}|r|ni }|D ]=}d}z!|j|i |}|j D ]\}}|j	| }|ot|j|}qW n ty   d}Y nw |rt||||} |S q|S 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if_trueif_falser   r   r!   TF
c                 s   s    | ]}t |V  qd S r%   )r    r   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:
)r   typesBuiltinFunctionTyper   r   r   r    r+   r,   r_   callableunwrap&_args_kwargs_to_normalized_args_kwargsr   rt   r*   ru   r\   r   r	   r   rR   itemsr   rL   joinr2   r1   typename)rn   r   r   r   r   r   new_args_and_kwargstarget_for_analysis
dispatchedr   r   sigtorch_op_schemasrw   rx   sig_matchesbound_typesarg_namera   paramschema_printoutsr!   r!   r"   r   X  s   

A-*

r   rootc           
   
   C   s   z|  |}W n ty } z	td| d|d}~ww t|jdrI|jj}ttj|d|jkrIt	
t	|j}|du r@i }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   )get_submoduleAttributeErrorr2   hasattr	__class__r   r|   r1   nnr+   r,   r   forwardr   )
r   rn   r   r   r   submode	classnamer   r   r!   r!   r"   r     s*   
r   r   .c           	         s   t jjt jjh t fdd| j D r#t| j g dkr#dS | j	|i |}|
  i }g }t| jD ]\}}|sM|t|k rM||j|  q8|j| ||< q8t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%   )rJ   )rN   rc   supported_parameter_typesr!   r"   r      r   z9_args_kwargs_to_normalized_args_kwargs.<locals>.<genexpr>)rH   rI   to	generatorN)r+   rG   rX   rW   r   r_   valuesr   keysrt   apply_defaultsrZ   r\   r*   rR   r   r]   )	r   r   r   r   
bound_args
new_kwargsnew_argsir   r!   r   r"   r     s   r   )F)NNNF)NF)Aenumr+   r   r   r   r   r   r   r   r   r   r   r   r	   r
   r1   torch._jit_internalr   
torch._opsr   r   _compatibilityr   noder   __all__r   r#   r^   r   r/   r'   r0   r6   devicelayoutr   r   r:   EnumqschemerM   UntypedStorageTypeVarrD   dirkr|   rE   r   FunctionSchemarf   rg   r    rm   r   r-   r   r   r   r   r   Moduler   r   r!   r!   r!   r"   <module>   s   
,		
3

'"
,1
z.

