
    קgcQ                     z   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 g dZ ed	
           G d de                      Zi Ze	ee
ej                 f         ed<   d Z e            ee j        <    G d d          Z e j!        e j"        e j#        ej$        e j%        j&        ej'        e j(         e              e)d          e j*         ej+        d          dZ, e-e          D ]Z. e/ee.          e,e.<   dddefdZ0de j1        j2        dej        fdZ3i Z4e	ee5e5f         ej        f         ed<   de j1        j2        dej        fdZ6 ed	
          deded         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ee         dee	e5ef                  d(eee                  d)ee	e5ef                  d*e8dee         fd+            Z< ed	
          	 	 d3d,e j=        j>        de5dee         dee	e5ef                  d*e8dee         fd-            Z?d.ej        deed/f         de	e5ef         d*e8dee         f
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)is_backward_compatiblec                   H    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     U/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/fx/operator_schemas.pyr   r      sF           S/cNr$   r   _manual_overridesc                      g } d }|                      t          j        |                     dt          fd}|                      t          j        |                     | S )Nc                     d S Nr#   )selfs    r%   nonzeroz!_nonzero_schemas.<locals>.nonzero!       r$   as_tuplec                    d S r)   r#   )r*   r-   s     r%   r+   z!_nonzero_schemas.<locals>.nonzero%   r,   r$   )appendinspect	signaturebool)
signaturesr+   s     r%   _nonzero_schemasr4      su    J  g'00111D    g'00111r$   c                       e Zd Zd ZdS )_FakeGlobalNamespacec                 :    |dk    rt           S t          d          )Ntorchz!Expected a torch namespace lookup)r8   RuntimeError)r*   names     r%   __getattr__z _FakeGlobalNamespace.__getattr__.   s    7??L>???r$   N)r   r   r   r;   r#   r$   r%   r6   r6   -   s(        @ @ @ @ @r$   r6   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)rG   s    r%    _torchscript_type_to_python_typerM   <   s     &(:;;;r$   	ts_schemac           	         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    ra||j        k    sJ |j        }t          |          D ]=\  }}	|	j        |j        k    sJ  ||	j        |j        |	j        |	j                  ||<   >|                     |||||                     d | j        D             }
t'          |
          dk    rd }n+t'          |
          dk    r	|
d         }nt)          |
          }t          j        ||	          S )
Nr   )	Parameterr*   inputfrom)r:   kinddefault
annotationc                 6    g | ]}t          |j                  S r#   )rM   type).0rets     r%   
<listcomp>z9_torchscript_schema_to_signature_impl.<locals>.<listcomp>\   s#    \\\34SX>>\\\r$   r   )return_annotation)r0   rP   	argumentsrM   rW   has_default_valuedefault_valueemptyr:   
kwarg_onlyKEYWORD_ONLYPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLY	enumeraterS   rT   rU   r/   returnslentuple	Signature)rN   rP   
parametersargarg_typerT   r:   rS   idxpreturn_typesreturn_types               r%   %_torchscript_schema_to_signature_implrp   D   s   !!!!!!#%J" a a3CH=='*'<'<'>'>S###IO 8v--sxx7),\y%%Y=\6>>9::::: ,D#J// E EQv!@@@@@"+)i>Wabajwx  xD  #E  #E  #E
3))D'V^___````\\)J[\\\L
<A	\		a		"1oL))Z;GGGGr$   _SCHEMA_TO_SIGNATURE_CACHEc                     | j         | j        f}t                              |          }||S t	          |           }|t          |<   |S r)   )r:   overload_namerq   getrp   )rN   	cache_key	cache_valress       r%    _torchscript_schema_to_signaturerx   h   sM    	 77I*..y99I
/	
:
:C,/y)Jr$   targetr   )r   .r   r   c                 l   t          | d          \  }}|r|rg }t          ||          D ]A\  }}	  |j        |i | |                    ||f           +# t          $ r
}Y d }~:d }~ww xY wd }	t          |          dk    rd S t          |          dk    r|d         \  }
} |	|           d S d S d S d S )NT)return_schemasc                 :    | 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_mutabler9   )schemas    r%   throw_if_mutablez5check_for_mutable_operation.<locals>.throw_if_mutable   s?      9" $8v $8 $8 $8 9 9 99 9r$   r   r   )r   zipbindr/   	TypeErrorrf   )ry   r   r   r3   schemasmatched_schemascandidate_signaturer~   er   _schema_to_checks               r%   r   r   s   s0   4VDQQQJ g 
 ,/z7+C+C 	 	'(#($9&999&&(;V'DEEEE   	9 	9 	9 1$$D!!Q&&!0!3A_----- D;   s   $A
A*%A*opr{   c                     t           t                    r	 j        g}nt           t                    r! fd                                 D             }not
                                         }|r|r|dfndS t          j        j	        
                               }||rdndS t          j                            |          }d |D             }|r||fn|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                 :    g | ]}t          |          j        S r#   )getattr_schema)rX   overloadr   s     r%   rZ   z.get_signature_for_torch_op.<locals>.<listcomp>   s&    PPPX72x((0PPPr$   N)NNc                 ,    g | ]}t          |          S r#   )rx   rX   r~   s     r%   rZ   z.get_signature_for_torch_op.<locals>.<listcomp>   s!    QQQv26::QQQr$   )
isinstancer   r   r   	overloadsr&   rt   r8   jit	_builtins_find_builtin_C_jit_get_schemas_for_operator)r   r{   r   overrideaten_fnr3   s   `     r%   r   r      s      "j!! B:,	B(	)	) BPPPPPPP$((,, 	@'5?Hd##4?)%33B77?#1;<<t;(88AAQQQQQJ$2BJ  
Br$   c                    	 t          | t          t          f          rt          | t                    rd }nd }t          |           dk    r |t                    S | d         }| D ]7}t          ||          rt          ||          r|}& |t                    c S  ||          S n.# t          $ r!}t          j        d|             Y d}~nd}~ww xY w| 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                     t           |          S r)   )r   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 N)	r   listrg   rf   r   
issubclass	Exceptionwarningswarn)r   r   	base_typer<   r   s        r%   r   r      s4   ^a$'' 	'!T"" )# # # #) ) )1vv{{x}}$!I ) )a++ )	1-- ) !II#8C==(((8I&&&%	'&  ^ ^ ^\YZ\\]]]]]]]]^ Hs%   AB+ AB+ 
B+ +
C5CCsignature_typeargument_typec                    t          | d|           }| u rdS |t          j        u r(| k    r"| j        }t	          fd|D                       S | t
          t                   u rt          u rdS t          | dd           t          t
          hv r| j        d         t          j	                  st          j        d|  d           dS t          dd           t          t
          hv rt          j        d                   S fd} |          S | t          u rt          j        u rdS | t          j        u rt          t"          hv rdS t          j	                  r$t          j	        |           rt          |           S dS )	N
__origin__Tc              3   8   K   | ]}t          |          V  d S r)   )r   )rX   cr   s     r%   	<genexpr>ztype_matches.<locals>.<genexpr>   s-      IIa<=11IIIIIIr$   r   z.Does not support nested parametric types, got z. Please file a bug.Fc                     t          | dd           t          t          hvrdS | j        }| j        dk    rdS t	          fd|D                       S )Nr   F)r#   Tc              3   J   K   | ]}|t           u pt          |          V  d S r)   )Ellipsisr   )rX   r   sig_el_types     r%   r   z=type_matches.<locals>.is_homogeneous_tuple.<locals>.<genexpr>   s6      XXXD*Q*D*DXXXXXXr$   )r   rg   r   __args__all)r<   	containedr   s     r%   is_homogeneous_tuplez*type_matches.<locals>.is_homogeneous_tuple   s_    q,--eU^CCu
IzU""tXXXXiXXXXXXr$   )r   typingUnionr   anyr   intr   r0   isclassr   r   r   r8   dtypenumbersNumberfloat)r   r   sig_origin_typesig_containedr   r   s    `   @r%   r   r      s   nlNKKO&&t &,&&>]+J+J&/IIII=IIIIIIc""}';';t~|T22tTlBB$-a0{++ 	Meeeeg g g5=,55$EEm4Q7EEE	Y 	Y 	Y 	Y 	Y $#M222 %+!=!=t''Mc5\,I,It}%% 9'/.*I*I 9-8885r$   	arg_typeskwarg_typesnormalize_to_only_use_kwargsc                 F   |i }d}t          | t          j                  st          | t          t          f          s| }| t
          v rlt          | t                    rJ t
          |          }|d         |d         }
}	t          j        |	          j	        t          j        |
          j	        k    rdS |	}t          |          sJ t          j        t          j        |                    }t          ||||          }nt          |           sJ t          |           }g }|r}|D ]<}	  |j        |i | |                    |           &# t           $ r
}Y d}~5d}~ww xY wt#          |          dk    rn)t#          |          dk    rt          |d         |||          }n|||r|nt%          t&          t(                   d          }|r|ni }|D ]}d}	  |j        |i |}|j                                        D ])\  }}|j	        |         }|ot/          |j        |          }*n# t           $ r}d}Y d}~nd}~ww xY w|rt          ||||          } nnFd	                    d
 |D                       }t5          dt7          j        |            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              3   4   K   | ]}t          |          V  d S r)   )r"   r   s     r%   r   z%normalize_function.<locals>.<genexpr>i  s(      0[0[V0[0[0[0[0[0[r$   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"   r0   r1   ri   callableunwrap&_args_kwargs_to_normalized_args_kwargsr   r   r/   r   rf   r
   r   r   r\   itemsr   rU   joinr9   r8   typename)ry   r   r   r   r   r   new_args_and_kwargstarget_for_analysis
dispatchedr   r   sigtorch_op_schemasr   r   r   sig_matchesbound_typesarg_namerk   paramschema_printoutss                         r%   r   r     s   6 ~fe788 @r6,j9::@r %'''
 "&#.....+F3J *9 5z*7MXG ))48I(8S8S8^^^t")+,,,,,/B C CDDDS$PVXtuu5f== )	r (8  #,',d=f===#**+>????    HHHH ?##q((_%%**&L_]^M_aegmMi'k 'k## (K,C-6 P		DsR<P<PI1<"D++"K/? " "+&*0*B*=*BI*]Q\*]*]K6A6K6Q6Q6S6S g g 2((;(Fx(P.9.fl5K[]e>f>fg  ) 0 0 0*/KKKKKK0& "2XYlnrtzYu3w 3w/!E" (,yy0[0[?0[0[0['['[$& (q%.Y_J`J` (q (q^n(q (q r r r s+   )"E
E E AH**
I 4H;;I rootc                    	 |                      |          }n&# t          $ r}t          d| d          |d}~ww xY wt          |j        d          rs|j        j        }t          t          j        |d          |j        k    rCt          j
        t          j        |j                            }|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AttributeErrorr9   hasattr	__class__r   r   r8   nnr0   r1   r   forwardr   )
r   ry   r   r   r   submodr   	classnamer   r   s
             r%   r   r   p  s    .8##F++ 8 8 8 0& 0 0 0 1 167	88 v,, '$-	58Y--1AAA#GN6>$B$BCCC~"HdTZIe#g #g&&4s    
;6;r   .c                 L  	 t           j        j        t           j        j        h	t	          	fd| j                                        D                       r.t          | j                                                  g dk    rdS  | j	        |i |}|
                                 i }g }t          | j                  D ]K\  }}|s4|t          |          k     r!|                    |j        |                    ;|j        |         ||<   Lt          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V  d S r)   )rS   )rX   rm   supported_parameter_typess     r%   r   z9_args_kwargs_to_normalized_args_kwargs.<locals>.<genexpr>  s+      
T
Tq1622
T
T
T
T
T
Tr$   )rQ   rR   to	generatorN)r0   rP   rb   ra   r   ri   valuesr   keysr   apply_defaultsrd   rf   r/   r\   r   rg   )
r   r   r   r   
bound_args
new_kwargsnew_argsir   r   s
            @r%   r   r     s.   0 	/1B1O!Q

T
T
T
TCN<Q<Q<S<S
T
T
TTT 
 ##%%&&*N*N*NNN44*6**J"$JHcn-- < <5+ 	<CIIOOJ078888 * 4U ;Ju%//:666r$   )F)NNNF)NF)Ar8   r0   r   r   r   enumr   r   r   r   r   r   r   r	   r
   r   torch._jit_internalr   _compatibilityr   
torch._opsr   r   noder   __all__r   r&   rh   r!   r4   r+   r6   r=   devicelayoutr   r   rA   EnumqschemerW   UntypedStorageTypeVarrL   dirkr   rM   r   FunctionSchemarp   rq   r"   rx   r   r2   r   r   r   r   r   Moduler   r   r#   r$   r%   <module>r      s          ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ 2 2 2 2 2 2 ) ) ) ) ) ) 3 3 3 3 3 3 3 3 E E E e,,,    Z   -, ?A D4(9#::; @ @ @   $4#3#5#5 %-  @ @ @ @ @ @ @ @ "'%,SXS_!(EI<L&*iU]#7#7#9#9ttDzz!&!5)6>#..0 0  
V / /A#GFA..q</A <c < < < < Heh6M  HRYRc  H  H  H  HD IK T%S/73D"DE J J J	1H 	WM^ 	 	 	 	 e,,,   %:P  [_`ceo`o[p       -, D e,,,C CH Ct C C C -,CB e,,,# # -,#J e,,,-# -s - - - -,-^ e,,,y}15.3_ __ %c
_5=d38n5M_bjkpqtkubv_tCH~._ (,_ 9A8P_ _ _ -,_B e,,,bf.3$ $ho$'*$27*$GOPTUXZ]U]P^G_$'+$8@8P$ $ $ -,$L,71B ,75QTVYQY? ,748cN,7JN,7S[\jSk,7 ,7 ,7 ,7 ,7 ,7r$   