o
    j9:j]                     @   sr  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 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 ddlmZ erUdd	lmZ g d
ZeddG dd deZi Zeedef eej f e d< deej f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edZ/e0eD ]	Z1e2ee1e/e1< qdddefddZ3dej4j5dejfddZ6i Z7ee8e9e9f ejf e d< dej4j5dejfd d!Z:eddd"edef d#e8d$ d%ee9d&f ddfd'd(Z;ed)edef d*e
d+ de8eej dB eej4j5 dB f fd,d-Z<e	dDd)edef d*e
d deej dB fd.d-Z<edd	dEd)edef d*e=deej e8eej dB eej4j5 dB f B dB fd/d-Z<eddd0e>de>fd1d2Z?eddd3ed4ede=fd5d6Z@edd				dFd"edef d#e8edf d%ee9ef dB d7e8e dB d8ee9ef dB d9e=defd:d;ZAedd				dFd"edef d#e8edf d%ee9ef dB d7e8e dB d8ee9ef dB d9e=dedB fd<d=ZBedd		dGd>ejCjDd"e9d#e8e d%ee9ef dB d9e=dedB fd?d@ZEdAejd#e8edf d%ee9ef d9e=dedB f
dBdCZFdS )H    N)Callable)AnycastLiteral
NamedTupleoverloadTYPE_CHECKING)boolean_dispatched)
OpOverloadOpOverloadPacket)
_fast_bind   )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__tupler   __annotations__dictstr r"   r"   `/home/nk/hobo-godmode/plappi-mvp/.venv/lib/python3.10/site-packages/torch/fx/operator_schemas.pyr       s   
 r   ._manual_overridesreturnc                  C   sT   g } dt jdd fdd}| t| dt jdtdd fdd}| t| | S )Nselfr%   c                 S      d S Nr"   )r&   r"   r"   r#   nonzero0      z!_nonzero_schemas.<locals>.nonzeroas_tuplec                S   r'   r(   r"   )r&   r+   r"   r"   r#   r)   5   r*   )torchTensorappendinspect	signaturebool)
signaturesr)   r"   r"   r#   _nonzero_schemas-   s   r3   c                   @   s    e Zd ZdedejfddZdS )_FakeGlobalNamespacenamer%   c                 C   s   |dkrt S td)Nr,   z!Expected a torch namespace lookup)r,   RuntimeError)r&   r5   r"   r"   r#   __getattr__A   s   z _FakeGlobalNamespace.__getattr__N)r   r   r   r!   types
ModuleTyper7   r"   r"   r"   r#   r4   @   s    r4   t)r-   DeviceLayoutnumberFutureAnyEnumTypeQScheme	__torch__NoneTypeStorager:   PyObjectts_typeztorch._C.JitTypec                 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)rE   r"   r"   r#    _torchscript_type_to_python_typeY   s   rI   	ts_schemac              	   C   s<  ddl m} g }| jD ]k}t|j}| r|jn|j}|jdkr$|jnd}|j	r,|j
n|j}|dkrk||jkr?td| |j}t|D ]$\}}	|	j|jkr\td|	j d|	j ||	j|j|	j|	jd	||< qF||||||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fromz$Expected POSITIONAL_OR_KEYWORD, got z)Expected POSITIONAL_OR_KEYWORD for param z, got )r5   kinddefault
annotationc                 S   s   g | ]}t |jqS r"   )rI   type).0retr"   r"   r#   
<listcomp>   s    
z9_torchscript_schema_to_signature_impl.<locals>.<listcomp>r   )return_annotation)r/   rK   	argumentsrI   rQ   has_default_valuedefault_valueemptyr5   
kwarg_onlyKEYWORD_ONLYPOSITIONAL_OR_KEYWORDAssertionErrorPOSITIONAL_ONLY	enumeraterN   rO   rP   r.   returnslenr   	Signature)rJ   rK   
parametersargarg_typerO   r5   rN   idxpreturn_typesreturn_typer"   r"   r#   %_torchscript_schema_to_signature_implb   sJ   



rj   _SCHEMA_TO_SIGNATURE_CACHEc                 C   s6   | j | jf}t|}|d ur|S t| }|t|< |S r(   )r5   overload_namerk   getrj   )rJ   	cache_key	cache_valresr"   r"   r#    _torchscript_schema_to_signature   s   
rq   targetr   )r   .r   r   c              	   C   s   t | dd\}}|r]|r_g }t||D ]!\}}zt|g|R i | |||f W q ty4   Y qw dtjjdd fdd}t|dkrHd S t|dkrZ|d \}	}
||
 d S 	 d S d S d S )	NT)return_schemasschemar%   c                 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_mutabler6   )rt   r"   r"   r#   throw_if_mutable   s
   
z5check_for_mutable_operation.<locals>.throw_if_mutabler   r   )	r   zipr   r.   	TypeErrorr,   _CFunctionSchemara   )rr   r   r   r2   schemasmatched_schemascandidate_signaturert   rv   _schema_to_checkr"   r"   r#   r      s$   r   oprs   Tc                 C   r'   r(   r"   r   rs   r"   r"   r#   r         r   c                 C   r'   r(   r"   r   r"   r"   r#   r      r   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)rR   r   r   r"   r#   rT      s    z.get_signature_for_torch_op.<locals>.<listcomp>N)NNc                 S   s   g | ]}t |qS r"   )rq   rR   rt   r"   r"   r#   rT     s    )
isinstancer
   r   r   	overloadsr$   rm   r,   jit	_builtins_find_builtinry   _jit_get_schemas_for_operator)r   rs   r{   overrideaten_fnr2   r"   r   r#   r      s   



xc                 C   s   zOt | ttfrMt | trdtdtfdd}n	dtdtfdd}t| dkr+|tW S | d }| D ]}t||r9q1t||rA|}q1|t  W S ||W S W | S  tya   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`.
    r   r%   c                 S   s   t |  S r(   )listr   r"   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   r   r   r   ra   
issubclass	Exceptionwarningswarn)r   r   	base_typer:   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 | dd tu ri| jd  tu r:tu r:dS tsJt	
d|  d dS t  dd tu rZt jd S d	td
tffdd}| S | tu rt tju rtd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   rR   c)r   r"   r#   	<genexpr>C      ztype_matches.<locals>.<genexpr>r   z.Does not support nested parametric types, got z. Please file a bug.Fr:   r%   c                    s>   t | tur	dS t | }|dkrdS t fdd|D S )NF)r"   Tc                 3   s"    | ]}|t u pt| V  qd S r(   )Ellipsisr   r   sig_el_typer"   r#   r   Z  s     z=type_matches.<locals>.is_homogeneous_tuple.<locals>.<genexpr>)typing
get_originr   get_argsall)r:   	containedr   r"   r#   is_homogeneous_tupleT  s   
z*type_matches.<locals>.is_homogeneous_tuple)r   r   Union__args__anyr   intr/   isclassr   r   r   objectr1   r,   dtypenumbersNumberfloat)r   r   sig_origin_typesig_containedr   r"   )r   r   r#   r   8  s4   


	
r   	arg_typeskwarg_typesnormalize_to_only_use_kwargsc                 C   s8   t | |||||}|du rtd|  d| d| |S )zb
    Wrapper around normalize_function that never returns None, but
    loudly errors instead
    NzFailed to normalize function z with args z and kwargs )r   r6   )rr   r   r   r   r   r   rp   r"   r"   r#   _normalize_function_or_errork  s   r   c              	   C   s~  |du ri }d}t | tjst | ttfst| dr| j} t | tjstt | ttfst| }| tv rVt | tr9t	dt|  }|d |d }	}
t
|	jt
|
jkrTdS |	}t|sct	dt| t
t
|}t||||}|S t| st	dt|  t| }g }|r=|D ]}zt|g|R i | || W q ty   Y qw 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 ]C}d}z%t|g|R i |}|j D ]\}}|j| }|ot|j|}qW n ty   d}Y nw |r#t||||} |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_opz"target should not be a string hereif_trueif_falsez*target_for_analysis must be callable, got ztarget must be callable, got r   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   r8   BuiltinFunctionTyper   r
   hasattrr   r	   r!   r]   r/   r0   rc   callablerQ   unwrap&_args_kwargs_to_normalized_args_kwargsr   r   r.   rx   ra   r   r   r   rV   itemsr   rP   joinr6   r,   typename)rr   r   r   r   r   r   new_args_and_kwargstarget_for_analysis
dispatchedr   r   sigtorch_op_schemasr|   r}   sig_matchesbound_typesarg_namere   paramschema_printoutsr"   r"   r#   r     s   
	


B-*

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AttributeErrorr6   r   	__class__r   r   r,   nnr/   r0   r   forwardr   )
r   rr   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 t	| g|R i |}|
  i }g }t| jD ]\}}|sP|t|k rP||j|  q;|j| ||< q;t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(   )rN   )rR   rg   supported_parameter_typesr"   r#   r   \  r   z9_args_kwargs_to_normalized_args_kwargs.<locals>.<genexpr>)rL   rM   to	generatorN)r/   rK   r\   r[   r   rc   valuesr   keysr   apply_defaultsr_   ra   r.   rV   r   r   )	r   r   r   r   
bound_args
new_kwargsnew_argsir   r"   r   r#   r   >  s   r   ).)F)NNNF)NF)Genumr/   r   r8   r   r   collections.abcr   r   r   r   r   r   r   r,   torch._jit_internalr	   
torch._opsr
   r   torch.utils._inspectr   _compatibilityr   noder   __all__r   r$   r    r   rb   r   r3   r)   r4   r-   devicelayoutr   r   r>   EnumqschemerQ   UntypedStorageTypeVarrH   dirkr   rI   ry   rz   rj   rk   r   r!   rq   r   r   r1   r   r   r   r   r   r   Moduler   r   r"   r"   r"   r#   <module>   sB  
  "		
9


)
 

 (,2





 .

