U
    ©Ê¹j@M  ã                   @   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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mZ ddlmZ d dlmZmZ eržddlmZ dd	d
ddddg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 *d¡dœ
Z+e,eƒD ]Z-e.ee-ƒe+e-< �qDdedœdd„Z/e j0j1ejdœdd„Z2edd�eed  e	e3d!f d"œd#d	„ƒZ4edd�d1ee5d$œd%d
„ƒZ6edd�d&d„ ƒZ7edd�eed'œd(d„ƒZ8edd�d2eee ee	e3ef  eee  ee	e3ef  e5ee d)œd*d„ƒZ9edd�d3e j:j;e3ee ee	e3ef  e5ee d+œd,d„ƒZ<ejeed-f e	e3ef e5ee d.œd/d0„Z=dS )4é    N)	ÚAnyÚCallableÚDictÚListÚOptionalÚTupleÚ
NamedTupleÚcastÚTYPE_CHECKING)Úboolean_dispatchedé   )Úcompatibility)ÚOpOverloadPacketÚ
OpOverload)Ú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__r   r   Ú__annotations__r   Ústr© r    r    úX/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/fx/operator_schemas.pyr      s   
Ú_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%   $   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   r1   r    r    r    r!   r-   ,   s   r-   Út)
ÚTensorZDeviceZLayoutÚnumberÚFutureZAnyEnumTypeZQSchemeZ	__torch__ZNoneTyper2   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)r6   r    r    r!   Ú _torchscript_type_to_python_type:   s    r:   )Ú	ts_schemar7   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stt‚|j}t|ƒD ]4\}}	|	j|jksšt‚||	j|j|	j|	jd�||< q‚| |||||d�¡ qdd„ | jD ƒ}
t|
ƒdkròd }n t|
ƒd	k�r
|
d }nt|
ƒ}t j||d
�S )Nr   )Ú	Parameterr$   ÚinputÚfrom)r0   ÚkindÚdefaultÚ
annotationc                 S   s   g | ]}t |jƒ‘qS r    )r:   Útype)Ú.0Úretr    r    r!   Ú
<listcomp>Z   s     z4_torchscript_schema_to_signature.<locals>.<listcomp>r   )Úreturn_annotation)r(   r<   Ú	argumentsr:   rB   Zhas_default_valueÚdefault_valueÚemptyr0   Z
kwarg_onlyÚKEYWORD_ONLYÚPOSITIONAL_OR_KEYWORDÚAssertionErrorÚPOSITIONAL_ONLYÚ	enumerater?   r@   rA   r'   ZreturnsÚlenÚtupleÚ	Signature)r;   r<   Ú
parametersÚargÚarg_typer@   r0   r?   ÚidxÚpZreturn_typesÚreturn_typer    r    r!   Ú _torchscript_schema_to_signatureB   s*    


rX   )r   .r   )Útargetr   r   c                 C   s¶   t | dd�\}}|r²|r²g }t||ƒD ]R\}}z|j||Ž | ||f¡ W q& tk
rv } zW Y ¢q&W 5 d }~X Y q&X q&dd„ }	t|ƒdkr�n"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_mutableu   s    z5check_for_mutable_operation.<locals>.throw_if_mutabler   r   )r   ÚzipÚbindr'   Ú	TypeErrorrO   )rY   r   r   r+   ÚschemasÚmatched_schemasÚcandidate_signaturer[   Úer\   Ú_Zschema_to_checkr    r    r!   r   d   s"    )ÚoprZ   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k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)rC   Úoverload©re   r    r!   rE   ›   s     z.get_signature_for_torch_op.<locals>.<listcomp>N)NNc                 S   s   g | ]}t |ƒ‘qS r    )rX   ©rC   r[   r    r    r!   rE   §   s     )Ú
isinstancer   rg   r   Z	overloadsr"   Úgetr.   ÚjitZ	_builtinsZ_find_builtinÚ_CZ_jit_get_schemas_for_operator)re   rZ   r`   ÚoverrideZaten_fnr+   r    ri   r!   r   ˆ   s    



c              
   C   sÄ   zŒt | ttfƒrŠt | 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 n2 tk
r¾ } zt d| › �¡ W 5 d }~X Y nX | S )Nc                 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   rp   r    r    r!   rr   ³   s    r   z@We were not able to successfully create type hint from the type )	rk   ÚlistrP   rO   r   Ú
issubclassÚ	ExceptionÚwarningsÚwarn)rq   rr   Z	base_typer2   rc   r    r    r!   r   ª   s&    




)Úsignature_typeÚargument_typec                    s.  t | d| ƒ}| ˆ krdS |tjkrF| ˆ krF| j}t‡ fdd„|D ƒƒS | tt kr^ˆ tkr^dS t | dd ƒtthkrÔ| jd ‰t 	ˆ¡sœt
 d| › d�¡ dS t ˆ dd ƒtthkrÀtˆ jd ˆƒS ‡fd	d
„}|ˆ ƒS | tkrêˆ tjkrêdS | tjk�rˆ tthk�rdS t 	ˆ ¡�r*t 	| ¡�r*tˆ | ƒS dS )NÚ
__origin__Tc                 3   s   | ]}t |ˆ ƒV  qd S r#   )r   ©rC   Úc)ry   r    r!   Ú	<genexpr>Ñ   s     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krdS | j}| jdkr,dS t‡ fdd„|D ƒƒS )Nrz   F)r    Tc                 3   s    | ]}|t kpt|ˆ ƒV  qd S r#   )ÚEllipsisrt   r{   ©Úsig_el_typer    r!   r}   æ   s     z=type_matches.<locals>.is_homogeneous_tuple.<locals>.<genexpr>)rf   rP   r   Ú__args__Úall)r2   Z	containedr   r    r!   Úis_homogeneous_tupleà   s    
z*type_matches.<locals>.is_homogeneous_tuple)rf   ÚtypingÚUnionr�   Úanyr   Úintrs   r(   Úisclassrv   rw   rt   r.   ZdtypeÚnumbersÚNumberÚfloat)rx   ry   Zsig_origin_typeZsig_containedrƒ   r    )ry   r€   r!   r   Æ   s4    


ÿ	
)rY   r   r   Ú	arg_typesÚkwarg_typesÚnormalize_to_only_use_kwargsr7   c                 C   sV  |dkri }d}t | tjƒs¬t | ttfƒs¬| }| tkr~t | tƒrDt‚t|  }|d |d  }	}
t 	|	¡j
t 	|
¡j
krzdS |	}t|ƒsŠt‚t 	t |¡¡}t||||ƒ}�n¦t| ƒs¸t‚t| ƒ}g }|�rR|D ]L}z|j||Ž | |¡ W qÎ tk
�r } zW Y ¢qÎW 5 d}~X Y qÎX qÎt|ƒdk�r.�n$t|ƒdk�rRt|d |||ƒ}�n |dk	�sf|dk	�r$|�rp|nttt dƒ}|�rˆ|ni }|D ]�}d}zB|j||Ž}|j ¡ D ]&\}}|j
| }|�oÒt|j|ƒ}�q°W n( tk
�r } zd}W 5 d}~X Y nX |�r�t||||ƒ} �qR�q�n.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   rj   r    r    r!   r}   Q  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:
)rk   ÚtypesÚBuiltinFunctionTyper   r   r   r   rL   r(   r)   rR   ÚcallableÚunwrapÚ&_args_kwargs_to_normalized_args_kwargsr   r^   r'   r_   rO   r	   r   r   rG   Úitemsr   rA   Újoinr/   r.   Útypename)rY   r   r   rŒ   r�   rŽ   Únew_args_and_kwargsZtarget_for_analysisZ
dispatchedr�   r�   ÚsigZtorch_op_schemasra   rb   rc   Zsig_matchesZbound_typesZarg_namerT   ÚparamZschema_printoutsr    r    r!   r   ö   sj    ÿÿ
ÿ)ÚrootrY   r   r   rŽ   r7   c           
   
   C   s    z|   |¡}W n4 tk
rB } ztd|› d�ƒ|‚W 5 d}~X Y nX t|jdƒrœ|jj}ttj|dƒ|jkrœt	 
t	 |j¡¡}|dk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   )Zget_submoduleÚAttributeErrorr/   ÚhasattrÚ	__class__r   rf   r.   Únnr(   r)   r•   Úforwardr–   )
r�   rY   r   r   rŽ   Zsubmodrc   Ú	classnamer›   rš   r    r    r!   r   X  s"    ÿÿ.)r›   r   r   rŽ   r7   c           	         s¸   t jjt jjh‰ t‡ fdd„| j ¡ D ƒƒrJt| j ¡ ƒddddgkrJdS | j	||Ž}| 
¡  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 ˆ kV  qd S r#   )r?   )rC   rV   ©Zsupported_parameter_typesr    r!   r}   ˜  s     z9_args_kwargs_to_normalized_args_kwargs.<locals>.<genexpr>r=   r>   ÚtoÚ	generatorN)r(   r<   rK   rJ   r†   rR   Úvaluesrs   Úkeysr^   Úapply_defaultsrN   rO   r'   rG   r   rP   )	r›   r   r   rŽ   Z
bound_argsZ
new_kwargsÚnew_argsÚirœ   r    r¤   r!   r–     s     ÿr–   )F)NNNF)NF)>r.   r(   r‰   r’   r„   Úenumrv   r   r   r   r   r   r   r   r	   r
   Ztorch._jit_internalr   Z_compatibilityr   Z
torch._opsr   r   Únoder   Ú__all__r   r"   rQ   r   r,   r%   r-   r3   ZdeviceZlayoutrŠ   rm   r5   ÚEnumZqschemerB   ÚTypeVarr9   ÚdirÚkrf   r:   rn   ZFunctionSchemarX   r   r   r*   r   r   r   r   r¡   ÚModuler   r–   r    r    r    r!   Ú<module>   s–    ,  ÿ   ü" #!
/     ý   
 ýa  þ    þ&
 þ