
    Vh4S                     P   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rddlmZ g dZ ed	
       G d de	             Zi Zeeeej6                     f   ed<   d Z e       eej<                  <    G d d      Zej@                  ejB                  ejD                  ejF                  ejH                  jJ                  e jL                  ejN                   e        e(d      ejR                   ejT                  d      dZ+ e,e      D ]  Z- e.ee-      e+e-<    dddefdZ/dej`                  jb                  dej6                  fdZ2i Z3ee4e5e5f   ej6                  f   ed<   dej`                  jb                  dej6                  fdZ6 ed	
      dede4d   dee5df   fd        Z7 ed	
      d1d!ed"e8fd#       Z9 ed	
      d$        Z: ed	
      d%ed&efd'       Z; ed	
      	 	 	 	 d2dede4ed(f   de
ee5ef      d)e
e4e      d*e
ee5ef      d+e8de
e   fd,       Z< ed	
      	 	 d3d-ejz                  j|                  de5de4e   de
ee5ef      d+e8de
e   fd.       Z?d/ej6                  de4ed(f   dee5ef   d+e8de
e   f
d0Z@y)4    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)is_backward_compatiblec                   :    e Zd ZU dZeedf   ed<   eeef   ed<   y)r   z<
    Simple named tuple for wrapping args/kwargs pairs.
    .argskwargsN)	__name__
__module____qualname____doc__tupler   __annotations__dictstr     I/home/dcms/DCMS/lib/python3.12/site-packages/torch/fx/operator_schemas.pyr   r      s%     S/cNr#   r   _manual_overridesc                      g } d }| j                  t        j                  |             dt        fd}| j                  t        j                  |             | S )Nc                      y Nr"   )selfs    r$   nonzeroz!_nonzero_schemas.<locals>.nonzero/       r#   as_tuplec                     y r(   r"   )r)   r,   s     r$   r*   z!_nonzero_schemas.<locals>.nonzero4   r+   r#   )appendinspect	signaturebool)
signaturesr*   s     r$   _nonzero_schemasr3   ,   sT    J g''014  g''01r#   c                       e Zd Zd Zy)_FakeGlobalNamespacec                 .    |dk(  rt         S t        d      )Ntorchz!Expected a torch namespace lookup)r7   RuntimeError)r)   names     r$   __getattr__z _FakeGlobalNamespace.__getattr__@   s    7?L>??r#   N)r   r   r   r:   r"   r#   r$   r5   r5   ?   s    @r#   r5   t)TensorDeviceLayoutnumberFutureAnyEnumTypeQScheme	__torch__NoneTypeStorager;   ts_typeztorch._C.JitTypereturnc                 6    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)rF   s    r$    _torchscript_type_to_python_typerL   W   s     &&(:;;r#   	ts_schemac           	      h   ddl m} g }| j                  D ]#  }t        |j                        }|j                         r|j                  n|j                  }|j                  dk7  r|j                  nd}|j                  r|j                  n|j                  }|dk(  r||j                  k(  sJ |j                  }t        |      D ]W  \  }}	|	j                  |j                  k(  sJ  ||	j                  |j                  |	j                  |	j                         ||<   Y |j#                   |||||             & | j$                  D 
cg c]  }
t        |
j                         }}
t'        |      dk(  rd }nt'        |      dk(  r|d   }nt)        |      }t        j*                  ||      S c c}
w )	Nr   )	Parameterr)   inputfrom)r9   kinddefault
annotationr   )return_annotation)r/   rO   	argumentsrL   typehas_default_valuedefault_valueemptyr9   
kwarg_onlyKEYWORD_ONLYPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLY	enumeraterR   rS   rT   r.   returnslenr   	Signature)rM   rO   
parametersargarg_typerS   r9   rR   idxpretreturn_typesreturn_types                r$   %_torchscript_schema_to_signature_implrk   `   s    ""$J"" 
3CHH='*'<'<'>###IOO 88v-sxx7 ~~ ""00 	 6>9::::: ,,D#J/ Qvv!@!@@@@"+"22II ||	#
3 	4dGQ	
;
B ?H>O>O7:(2L  <A	\	a	"1oL)Z;GGs   
F/_SCHEMA_TO_SIGNATURE_CACHEc                     | j                   | j                  f}t        j                  |      }||S t	        |       }|t        |<   |S r(   )r9   overload_namerl   getrk   )rM   	cache_key	cache_valress       r$    _torchscript_schema_to_signaturers      sN     	 7 77I*..y9I
/	
:C,/y)Jr#   targetr   )r   .r   r   c                 (   t        | d      \  }}|rq|rng }t        ||      D ]+  \  }}	  |j                  |i | |j                  ||f       - d }t        |      dk(  ry t        |      dk(  r|d   \  }	}
 ||
       y y y y # t        $ r Y mw xY w)NT)return_schemasc                 :    | j                   rt        d|  d      y )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_mutabler8   )schemas    r$   throw_if_mutablez5check_for_mutable_operation.<locals>.throw_if_mutable   s/      "7x @( )  !r#   r   r   )r   zipbindr.   	TypeErrorra   )rt   r   r   r2   schemasmatched_schemascandidate_signaturery   rz   _schema_to_checks              r$   r   r      s     5VDQJg
 ,/z7+C 	'(#(($9&9&&(;V'DE		 1$!Q&!0!3A_- ? z  s   %B	BBoprv   c                    t        | t              r| j                  g}nt        | t              r2| j	                         D cg c]  }t        | |      j                   }}not        j                  |       }|r|r|dfS dS t        j                  j                  j                  |       }||rdS dS t        j                  j                  |      }|D cg c]  }t        |       }}|r||fS |S c c}w c c}w )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
    N)NN)
isinstancer
   _schemar   	overloadsgetattrr%   ro   r7   jit	_builtins_find_builtin_C_jit_get_schemas_for_operatorrs   )r   rv   r~   overloadoverrideaten_fnry   r2   s           r$   r   r      s      "j!::,	B(	)ACPX72x(00PP$((,'5Hd#?4?))%%33B7?#1<;t;((88AIPQv26:QJQ$2J B
B Q Rs   C0C5c                 b   	 t        | t        t        f      rnt        | t              rd }nd }t        |       dk(  r |t              S | d   }| D ]+  }t        ||      rt        ||      r|} |t              c S   ||      S 	 | S # t        $ r t        j                  d|         Y | S w xY 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                     t         |    S r(   )listxs    r$   ret_typez"create_type_hint.<locals>.ret_type  s    7Nr#   c                     t         | df   S )N.)r   r   s    r$   r   z"create_type_hint.<locals>.ret_type  s     C=(r#   r   z@We were not able to successfully create type hint from the type )	r   r   r   ra   r   
issubclass	Exceptionwarningswarn)r   r   	base_typer;   s       r$   r   r      s    
a$'!T"#
) 1v{}$!I )a+	1- !I#C=() I&&- (8 H  
NqcR	
 H
s   AB	 	3B	 =B	 	!B.-B.signature_typeargument_typec                    t        | d|       }| u ry|t        j                  u r%| k7  r | j                  }t	        fd|D              S t        | dd       t
        u r| j                  d   t        u r	t        u ryt        j                        st        j                  d|  d       yt        dd       t
        u rt        j                  d         S fd} |      S | t        u rt        j                  u ry| t        j                  u rt        t         hv ryt        j                        r!t        j                  |       rt        |       S y)	N
__origin__Tc              3   6   K   | ]  }t        |        y wr(   )r   ).0cr   s     r$   	<genexpr>ztype_matches.<locals>.<genexpr>'  s     Ia<=1Is   r   z.Does not support nested parametric types, got z. Please file a bug.Fc                     t        | dd       t        ury| j                  }| j                  dk(  ryt        fd|D              S )Nr   F)r"   Tc              3   J   K   | ]  }|t         u xs t        |        y wr(   )Ellipsisr   )r   r   sig_el_types     r$   r   z=type_matches.<locals>.is_homogeneous_tuple.<locals>.<genexpr>>  s$     XXD*Q*DDXs    #)r   r   __args__all)r;   	containedr   s     r$   is_homogeneous_tuplez*type_matches.<locals>.is_homogeneous_tuple8  s@    q,-U:

IzzU"XiXXXr#   )r   typingUnionr   anyr   intr/   isclassr   r   r   r7   dtypenumbersNumberfloat)r   r   sig_origin_typesig_containedr   r   s    `   @r$   r   r     sB   nlNKO& &,,&>]+J&//I=III~|T2d:$--a0 CK3$6{+MM@@PPde =,5=m44Q7EE	Y $M22 %++!='Mc5\,I}%'//.*I-88r#   .	arg_typeskwarg_typesnormalize_to_only_use_kwargsc                    |i }d}t        | t        j                        st        | t        t        f      s| }| t
        v rgt        | t              rJ t
        |    }|d   |d   }
}	t        j                  |	      j                  t        j                  |
      j                  k7  ry|	}t        |      sJ t        j                  t        j                  |            }t        ||||      }|S t        |       sJ t        |       }g }|r;|D ]&  }	  |j                  |i | |j                  |       ( t#        |      dk(  r	 |S t#        |      dk(  rt        |d   |||      }|S |||r|nt%        t&        t(           d      }|r|ni }|D ]v  }d}	  |j                  |i |}|j*                  j-                         D ].  \  }}|j                  |   }|xr t/        |j0                  |      }0 	 |sgt        ||||      } |S  |S d	j3                  d
 |D              }t5        dt7        j8                  |        d|       |S # t         $ r Y Gw xY w# t         $ r d}Y rw xY w)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              3   2   K   | ]  }t        |        y wr(   )r!   )r   ry   s     r$   r   z%normalize_function.<locals>.<genexpr>  s      1(.F1s   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/   r0   rc   callableunwrap&_args_kwargs_to_normalized_args_kwargsr   r|   r.   r}   ra   r   r   r   rV   itemsr   rT   joinr8   r7   typename)rt   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_printoutss                        r$   r   r   O  s   > ~fe7786,j9:$''
 "&#...+F3J *9 5z*7MXG!!'*55$$X.99: ")+,,,/B CDDv;
B { 5f= (8 #,',,d=f=#**+>? ?#q(Z Y _%*&L#A&f6R'#T M (K,C-6	DsR<PI1<+"K/? "+&*
0*B*=*B*B!*+.9+K 7B6K6K6Q6Q6S " 2((;(F(Fx(P.9 /"l$)$4$4h?"" ' F$7$($*$@	!" 0 " G"F  (,yy 12A1 ($ ':5>>&;Q:R SOO_N`b  e ! 4  ) 0*/K0s%   #IAI	III%$I%rootc                    	 | j                  |      }t        |j                  d      r|j                  j
                  }t        t        j                  |d      |j                  k(  rFt        j                  t        j                  |j                              }|i }t        ||||      }	|	S y# t        $ r}t        d| d      |d}~ww xY w)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AttributeErrorr8   hasattr	__class__r   r   r7   nnr/   r0   r   forwardr   )
r   rt   r   r   r   submode	classnamer   r   s
             r$   r   r     s    6##F+ v,$$--	588Y-1A1AA##GNN6>>$BCC~"HT6#?# '&  26( ;  !
 	s   B. .	C7CCr   c                 H  	 t         j                  j                  t         j                  j                  h	t	        	fd| j
                  j                         D              r)t        | j
                  j                               g dk7  ry | j                  |i |}|j                          i }g }t        | j
                        D ]F  \  }}|s-|t        |      k  r|j                  |j                  |          5|j                  |   ||<   H 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   :   K   | ]  }|j                   v  y wr(   )rR   )r   rg   supported_parameter_typess     r$   r   z9_args_kwargs_to_normalized_args_kwargs.<locals>.<genexpr>  s     
Tq16622
Ts   )rP   rQ   to	generatorN)r/   rO   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   s
            @r$   r   r     s    6 	//&&! 
TCNN<Q<Q<S
TT
 ##%&*NN4*6*J!#JHcnn- <5+CIOOJ0078 * 4 4U ;Ju	< %/:66r#   )F)NNNF)NF)Aenumr/   r   r   r   r   r   r   r   r   r   r   r7   torch._jit_internalr	   
torch._opsr
   r   _compatibilityr   noder   __all__r   r%   r    r   rb   r   r3   r*   r5   r<   devicelayoutr   r   r@   EnumqschemerW   UntypedStorageTypeVarrK   dirkr   rL   r   FunctionSchemark   rl   r   r!   rs   r   r1   r   r   r   r   r   Moduler   r   r"   r#   r$   <module>r      s         K K  2 3 )  e,Z  - >@ 4$w'8'8"99: ?  $4#5 %--  @ @ llllllnnii99}}%'T
##		  
V /A#FA.q/<.@ <S <0Hxx&&0H0Hf HJ DsCx'2C2C!CD Ixx&& e,$$!/2$<@j<Q$ -$N e,C8 CT C -CD e,) -)X e,/ /S / -/d e, (,&*,0).ww
S/w T#s(^$w c
#	w
 $sCx.)w #'w nw -wt e,
 (,).+
((//++ *+ T#s(^$	+
 #'+ n+ -+\17			17
S/17 cN17 #'	17
 n17r#   