
    ǄgcQ                     V   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j8                     f   ed<   d Z e       ee j>                  <    G d d      Z e jB                  e jD                  e jF                  ejH                  e jJ                  jL                  ejN                  e jP                   e         e)d      e jT                   ejV                  d      dZ, e-e      D ]  Z. e/ee.      e,e.<    dddefdZ0de jb                  jd                  dej8                  fdZ3i Z4e	ee5e5f   ej8                  f   ed<   de jb                  jd                  dej8                  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 jz                  j|                  de5dee   dee	e5ef      d*e8dee   fd-       Z?d.ej8                  deed/f   de	e5ef   d*e8dee   f
d0Z@y)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                   :    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__r   r   __annotations__r   str     a/home/mcse/projects/flask_80/flask-venv/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>.nonzero%   r,   r$   )appendinspect	signaturebool)
signaturesr+   s     r%   _nonzero_schemasr4      sP    Jg''01D 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)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           	      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)r:   kinddefault
annotationr   )return_annotation)r0   rP   	argumentsrM   type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retreturn_typesreturn_types                r%   %_torchscript_schema_to_signature_implrm   D   s   !#%J"" a3CHH='*'<'<'>###IOO 88v-sxx7),y%%Y=\=\6>9::::: ,,D#J/ EQvv!@!@@@@"+i>W>Wabajajwx  xD  xD  #E
3E 	)D'V^_`)a* KTJ[J[\34SXX>\L\
<A	\	a	"1oL)Z;GG ]s   
F/_SCHEMA_TO_SIGNATURE_CACHEc                     | j                   | j                  f}t        j                  |      }||S t	        |       }|t        |<   |S r)   )r:   overload_namern   getrm   )rN   	cache_key	cache_valress       r%    _torchscript_schema_to_signatureru   h   sL    	 7 77I*..y9I
/	
:C,/y)Jr$   targetr   )r   .r   r   c                 6   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 d }~pd }~ww 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_mutabler9   )schemas    r%   throw_if_mutablez5check_for_mutable_operation.<locals>.throw_if_mutable   s/      "%Fvh O7 $8 9 9 !r$   r   r   )r   zipbindr/   	TypeErrorrb   )rv   r   r   r3   schemasmatched_schemascandidate_signaturer{   er|   _schema_to_checks               r%   r   r   s   s    4VDQJg
 ,/z7+C 	'(#(($9&9&&(;V'DE		9 1$!Q&!0!3A_- ; z  s   %B	BBoprx   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&   rq   r8   jit	_builtins_find_builtin_C_jit_get_schemas_for_operatorru   )r   rx   r   overloadoverrideaten_fnr{   r3   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                 p   	 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 d}~| S d}~w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)   )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   listrc   rb   r   
issubclass	Exceptionwarningswarn)r   r   	base_typer<   r   s        r%   r   r      s    ^a$'!T"#)1v{}$!I )a+	1- !I#C=() I&&% (, H  ^XYZX[\]]H^s$   AB	 	3B	 =B	 		B5B00B5signature_typeargument_typec                    t        | d|       }| u ry|t        j                  u r%| k7  r | j                  }t	        fd|D              S | t
        t           u r	t        u ryt        | dd       t        t
        hv r}| j                  d   t        j                        st        j                  d|  d       yt        dd       t        t
        hv 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        t        hv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   rc   r   __args__all)r<   	containedr   s     r%   is_homogeneous_tuplez*type_matches.<locals>.is_homogeneous_tuple   sD    q,-eU^C

IzzU"Xi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      sK   nlNKO& &,,&>]+J&//I=IIIc"}';~|T2tTlB$--a0{+MM@@PPdeg=,5$E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 d}~Jd}~ww xY w# t         $ r}d}Y d}~|d}~ww 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   r{   s     r%   r   z%normalize_function.<locals>.<genexpr>i  s     0[V0[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"   r0   r1   re   callableunwrap&_args_kwargs_to_normalized_args_kwargsr   r~   r/   r   rb   r
   r   r   rW   itemsr   rU   joinr9   r8   typename)rv   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_namerg   paramschema_printoutss                         r%   r   r     s   6 ~fe7786,j9:$''
 "&#...+F3J *9 5z*7MXG  )448I8I(8S8^8^^")+,,,/B CDDS$PVXtu` ] 5f= (8 #,',,d=f=#**+>? ?#q(< ; _%*&L_]^M_aegmMi'k#6 1 (K,C-6	DsR<PI1<+"K/? "+&*0*B*=*B*BI*]Q\*]K6A6K6K6Q6Q6S g 2((;(F(Fx(P.9.fl5K[K[]e>fg
 '2XYlnrtzYu3w/! +"*  (,yy0[?0['[$&)I%..Y_J`Ia b^^n]o(q r r G ! *  ) 0*/K0s+   #IAI	II	I3'I..I3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AttributeErrorr9   hasattr	__class__r   r   r8   nnr0   r1   r   forwardr   )
r   rv   r   r   r   submodr   	classnamer   r   s
             r%   r   r   p  s    .8##F+ v,$$--	588Y-1A1AA##GNN6>>$BCC~"HdTZIe#g&&  8A& J/ 0 167	88s   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)   )rS   )r   ri   supported_parameter_typess     r%   r   z9_args_kwargs_to_normalized_args_kwargs.<locals>.<genexpr>  s     
Tq16622
Ts   )rQ   rR   to	generatorN)r0   rP   r^   r]   r   re   valuesr   keysr~   apply_defaultsr`   rb   r/   rW   r   rc   )
r   r   r   r   
bound_args
new_kwargsnew_argsir   r   s
            @r%   r   r     s    0 	//1B1B1O1O!Q

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)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&   rd   r!   r4   r+   r6   r=   devicelayoutr   r   rA   EnumqschemerX   UntypedStorageTypeVarrL   dirkr   rM   r   FunctionSchemarm   rn   r"   ru   r   r2   r   r   r   r   r   Moduler   r   r#   r$   r%   <module>r      s          ^ ^ ^ 2 ) 3E e,Z  - ?A D4(9(9#::; @ $4#5 %--  @ @ "'%,,SXS_S_!(EII<L<L&*iiU]]#7#9tDz!&!5!5)6>>#.0  
V /A#FA.q/</A <c < Hehh6M6M  HRYRcRc  HD IK T%S/73D3D"DE J	1H1H 	WM^M^ 	 e,   %:P  [_`ceo`o[p   - D e,CH Ct C -CB e,# -#J e,-# -s - --^ e,y}15.3__ %c
_5=d38n5M_bjkpqtkubv_tCH~._ (,_ 9A8P_ -_B e,bf.3$hhoo$'*$27*$GOPTUXZ]U]P^G_$'+$8@8P$ -$L,71B1B ,75QTVYQY? ,748cN,7JN,7S[\jSk,7r$   