
    N jF                        S r SSKrSSKrSSKJrJrJr  SSKJrJ	r	J
r
Jr  SSKJr  SSKrSSKJs  Jr  SSKJr  SSKJrJrJrJrJrJr  SSKJr  S	S
KJr  S	SK J!r!  S	SK"J#r#J$r$J%r%  S	SK&J'r'  S	SKJ(r(  SSK)J*r*  SSK+J,r,  SSK-J.r.  SSK/J0r0  SSK1J2r2  SSK3J4r4J5r5  \
(       a  SSK6J7r7  \" S5      r8\" S5      r9S\:S\\\8\94   /\\8\94   4   4S jr; " S S\55      r< " S S\45      r=g) a  
This module implements variable tracking for TorchScript objects during Dynamo tracing.

The TorchScriptObjectVariable class provides specialized handling for TorchScript
objects with strong safety guarantees by:
- Enforcing method-call-only access to prevent unsafe attribute manipulation
- Converting graph breaks into hard errors via _raise_hard_error_if_graph_break
- Proper proxy and source tracking for TorchScript method calls
- Integration with higher-order operators for method call handling

Key safety features:
- Strict validation that only method calls are allowed (no direct attribute access)
- Immediate error reporting for potentially unsafe operations
- Proper source tracking for debugging and guard installation
- Safe handling of TorchScript object method calls through torchbind

The module ensures that TorchScript objects are handled safely during tracing
by limiting operations to known-safe patterns and failing fast for unsafe usage.
    N)CallableIterableSequence)AnyOptionalTYPE_CHECKINGTypeVar)	ParamSpec)Source)get_member_typeis_opaque_reference_typeis_opaque_typeis_opaque_value_type
MemberTypeshould_hoist)Proxy   )graph_break_hints)	skip_code)unimplementedUnsafeScriptObjectErrorUnsupported)
AttrSource)proxy_args_kwargs   )VariableTracker)ConstantVariable)ConstDictVariable)TupleVariable)LambdaVariable)UserDefinedObjectVariableUserDefinedVariableInstructionTranslator_P_Treasonreturnc                 \    S[         [        [        4   S[         [        [        4   4S jnU$ )Nfnr(   c                    ^  [         R                  " T 5      S[        R                  S[        R                  S[
        4U 4S jj5       nU$ )Nargskwargsr(   c                  f   >  T" U 0 UD6$ ! [          a  n[        UR                  5      UeS nAff = fN)r   r   msg)r,   r-   er*   s      v/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/torch/_dynamo/variables/script_object.pygraph_break_as_hard_errorQ_raise_hard_error_if_graph_break.<locals>.deco.<locals>.graph_break_as_hard_error@   s9    <4*6** <-aee4!;<s    
0+0)	functoolswrapsr%   r,   r-   r&   )r*   r3   s   ` r2   deco._raise_hard_error_if_graph_break.<locals>.deco?   sC    			<RWW 	<		 	<b 	< 
	< )(    )r   r%   r&   )r'   r7   s     r2    _raise_hard_error_if_graph_breakr:   <   s.    )"b&! )hr2v&6 ) Kr9   c                      ^  \ rS rSrSrS\S\SS4U 4S jjrS\4S jrS\4S	 jr	S\4S
 jr
S\4S jrS\4S jrSSS\S\4S jrSSS\\   S\\\4   S\4S jrSrU =r$ )OpaqueObjectClassVariableL   z
A variable that represents an opaque object class (not instance).
Since UserDefinedClassVariable has some special handling for side effects,
we have a separate class here which will directly return the object when
__init__ is called.
valuer-   r(   Nc                 2   > [         TU ]  " S0 UD6  Xl        g )N )super__init__r>   )selfr>   r-   	__class__s      r2   rB   "OpaqueObjectClassVariable.__init__T   s    "6"
r9   c                     U R                   $ r/   r>   rC   s    r2   as_python_constant,OpaqueObjectClassVariable.as_python_constantX       zzr9   c                     g)NFr@   rH   s    r2   is_python_constant,OpaqueObjectClassVariable.is_python_constant[   s     r9   c                 ,    [        U R                  5      $ r/   )r   r>   rH   s    r2   is_python_hashable,OpaqueObjectClassVariable.is_python_hashablea   s    #DJJ//r9   c                     U R                   $ r/   rG   rH   s    r2   as_proxy"OpaqueObjectClassVariable.as_proxyd   rK   r9   c                 N    U R                   R                   SU R                   S3$ )N())rD   __name__r>   rH   s    r2   __repr__"OpaqueObjectClassVariable.__repr__g   s$    ..))*!DJJ<q99r9   txr$   namec                    S n [         R                  " U R                  U5      n[        U[        5      (       a  UR                  U R                  5      nO[        U[        5      (       a  UR                  S U R                  5      nOq[        US
5      (       a`  [        U5      R                  nUS:X  a  UR                  S U R                  5      nO([	        SSU R                   SU SU 3SU SU S3SS/S	9  [        R                  " U5      (       a  [        R                  " U5      $ U R                  (       a  [!        U R                  U5      OS n["        R$                  " XU5      $ ! [         aL    [	        SSU R                   SU 3SU SU R                   S3SU S[        U R                  5       S3/S	9   GNf = f)Nz#Attribute not found on opaque classzclass=, attr=zThe attribute 'z!' does not exist on opaque class .zEnsure 'z' is a valid attribute of gb_typecontextexplanationhints__get__pybind11_static_propertyz&Unsupported descriptor on opaque classz, descriptor=z' is a descriptor of type 'z' which is not supported.zHOnly staticmethod, property, and pybind11_static_property are supported.zAConsider accessing this attribute outside of the compiled region.)inspectgetattr_staticr>   AttributeErrorr   type
isinstancestaticmethodre   propertyhasattrrX   r   
is_literalcreatesourcer   r   build)rC   r[   r\   obj	type_namerq   s         r2   var_getattr%OpaqueObjectClassVariable.var_getattrj   s   
	((T:C c<((++djj)CX&&++dDJJ/CS)$$ S	**I66kk$

3D$TZZLv]9+V"1$7RS\R]]v wb[	 &&s++#**3//26++DKK.4$$Rf55G  	= GD6:-dV3TUYU_U_T``abtf$>tDJJ?O>PPQR		s   !E* *AG ?G r,   c           	      p   [        U R                  5      (       aD  [        U R                  R                  R                  5        [        SSU R                   S3SS/S9  [        [        U5      5      n[        UR                  5        VVs0 s H  u  pV[        U5      U_M     snn5      nUR                  5       nUR                  5       n	U R                  " U0 U	D6n
[        R                  R                  R                  UR                   R"                  U
5      n[$        R'                  XX45      $ s  snnf )Nz:An opaque object was created in the middle of the program.Opaque object type: r_   z}Opaque objects cannot be created inside the torch.compile region. They must be created before entering the compiled function.zsPlease create the opaque object before calling torch.compile and pass it in as an argument or as a global variable.r`   )r   r>   r   rB   __code__r   r   listr   itemsr   rI   torch_libraryfake_class_registrymaybe_to_fake_objoutput	fake_modeTorchScriptObjectVariablerp   )rC   r[   r,   r-   var_argskv
var_kwargsconstant_argsconstant_kwargs
opaque_objfake_script_objs               r2   call_function'OpaqueObjectClassVariable.call_function   s    $DJJ//djj))223T.tzzl!<RM !d,&06?a !#?

 !335$779ZZ
-

  ..<<NNII
 )//-)I
 	
 @s   D2
rG   )rX   
__module____qualname____firstlineno____doc__r   rB   rI   boolrM   rP   rS   strrY   r   ru   r   dictr   __static_attributes____classcell__rD   s   @r2   r<   r<   L   s    c S T C D 0D 0# :# :'65 '6S '6_ '6R(
#(
 '(
 S/)*	(

 
(
 (
r9   r<   c                   \  ^  \ rS rSr% 0 r\\S 4   \S'   \S\	S\
4S j5       r\ SS\S\S	\S
\SS 4
S jj5       r  SS\S\S	\S\\   S\SS4U 4S jjjrS\4S jr\" S5      SSS\S\4U 4S jj5       r\" S5      SSS\S\\   S\\\4   S\4
S j5       rS\4U 4S jjrS\
4S jrSrU =r$ )r      _fake_script_object_cacheuser_clsr(   c                 Z    [        U[        R                  5      =(       d    [        U5      $ r/   )
issubclassr|   ScriptObjectr   )clsr   s     r2   is_matching_cls)TorchScriptObjectVariable.is_matching_cls   s    (E$6$67S>(;SSr9   Nproxyr>   ctor_args_kwargsoptionsc                     [        XU40 UD6$ r/   )r   )r   r>   r   r   s       r2   rp    TorchScriptObjectVariable.create   s     )7GS7SSr9   rq   r-   c                    > [         TU ]  " U40 UD6  Xl        [        U R                  [        R
                  R                  5      (       a"  X R                  R                  R                  S'   X@l	        X0l
        g )Nexample_value)rA   rB   r   rk   r|   fxr   nodemetarq   r   )rC   r   r>   r   rq   r-   rD   s         r2   rB   "TorchScriptObjectVariable.__init__   sX     	)&)
djj%((..1149JJOO  1 !1r9   c                    [        U R                  [        R                  R                  5      (       d  [        [        U R                  5      5      (       d   e[        [        U R                  5      5      (       a  SSKJ	n  UR                  " 5       nU R                  S   (       a  [        S5      eUR                  R                  [        U R                  5      U R                  S   5      nUR                  5       U l        U R                  $ )Nr   r#   r   zCNYI: hoisted opaque objects that accept kwargs, please pass as args)rk   r   r|   r   r   r   rj   r   torch._dynamo.symbolic_convertr$   
current_txr   RuntimeErrorr   synthetic_graph_inputrS   )rC   r$   r[   
hoisted_vts       r2   rS   "TorchScriptObjectVariable.as_proxy   s    $**ehhnn55 (TZZ(89999D,--P*557 ((+&]   YY<<$d&;&;A&>
 (002
zzr9   z<Dynamo cannot safely trace script object due to graph break.r[   r$   r\   c           
      V  >^ ^^ SSK Jn  SSKJn  [	        T R
                  S5      (       Ga3  [        T R
                  R                  5      (       Ga  T R
                  R                  n[        [        U5      T5      nUc  [        SSU ST 3S	T S
3ST S3/S9  U[        R                  :X  aH  [        UT5      n[        R                   " U5      (       a  [#        UU U4S j5      $ [$        T	T ]M  TT5      $ U[        R(                  :X  aU  [        UT5      n[        R                   " U5      (       a  T R*                  c  [#        UU U4S j5      $ [$        T	T ]M  TT5      $ [        T R
                  TS 5      nUcO  [        SST R
                   ST 3ST R
                   ST S3ST ST R
                   S3/[,        R.                  QS9  [1        U5      (       d  [        SST R
                   ST 3SS/S9  T R*                  c   eUR3                  U[5        T R*                  T5      T TS9$ )Nr   )call_torchbindr   ) TorchHigherOrderOperatorVariablescript_class_name:Attempted to access unregistered member on an OpaqueObjectvalue=r^   Member '0' is not registered for this opaque object type.
Register '9' with a MemberType in register_opaque_type(members=...).r`   c                  *   > TR                  TTX5      $ r/   call_methodr,   r-   r\   rC   r[   s     r2   <lambda>7TorchScriptObjectVariable.var_getattr.<locals>.<lambda>      0@0@T40Xr9   c                  *   > TR                  TTX5      $ r/   r   r   s     r2   r   r     r   r9   z.FakeScriptObject missing method implementation	, method=zTorchScript object z doesn't define the method r_   zEnsure the method z is implemented in z@Attempted to access non-callable attribute of TorchScript objectzWAttribute accesses of TorchScript objects to non-callable attributes are not supported.z-Use method calls instead of attribute access.)rq   script_obj_varmethod_name)!torch._higher_order_ops.torchbindr   higher_order_opsr   rn   r>   r   r   real_objr   rj   r   r   USE_REALgetattrrg   ismethodr    rA   ru   INLINEDrq   r   
USER_ERRORcallablemaker   )
rC   r[   r\   r   r   r   member_typer>   methodrD   s
   ```      r2   ru   %TorchScriptObjectVariable.var_getattr   s;    	EF4::233JJ((9
 9
 zz**H)XK "X$XJgdV<"*4&0` a$TF*cd	 j111$/##E**)X  !7.r488
 2 22$/##E**t{{/B *X  w*2t44T40>H IdV<1$**=XY]X^^_`(.A$**QO&11	 Z IdV<uC	 {{&&&/44dkk40	 5 
 	
r9   r,   c           	      ~   SSK Jn  [        U R                  S5      (       Ga  [	        U R                  R
                  5      (       Ga  U R                  R                  n[        U5      n[        UU5      nUc  [        SSU SU 3SU S3S	U S
3/S9  U[        R                  :X  a=  [        X45      u  pUR                  R                  SUU R                  /U	Q7U
S9nU" XS9$ U[        R                   :X  Ga   ["        R$                  " USS 5      b  [        SUR&                   S3S/ S9  U Vs/ s H  oR)                  5       PM     nnUR+                  5        VVs0 s H  u  pXR)                  5       _M     nnn[-        Xb5      nUS:X  a
  U" U0 UD6  U$ U" U0 UD6n[/        S [0        R2                  " U5       5       5      (       a  [        SSU SU S3SSU S3/S9  [4        R6                  " UU5      $ [        SSU SU SU 3SU S3/ S9  [        S SU R                   S!U 3S"U S#3S$/S9  g s  snf s  snnf )%Nr   )wrap_fx_proxyr   r   r   r^   r   r   r   r   r`   r   )r,   r-   )r[   r   __getattr__z3Opaque object with custom __getattr__ not supportedz with custom __getattr__zLDynamo does not support opaque objects types with custom __getattr__ methods__setattr__c              3   J   #    U  H  n[        [        U5      5      v   M     g 7fr/   )r   rj   ).0rs     r2   	<genexpr>8TorchScriptObjectVariable.call_method.<locals>.<genexpr>  s#      = -T!W55=s   !#zWOpaque object member with method-type USE_REAL returned a reference-type opaque object.rx   z. Method name: ''zTo properly guard reference-type opaque objects, we must lift them as inputs to the graph. In order to do this, they must all have a source, meaning they come from a global value or are an attribute of an input.zRegister member 'zM' with MemberType.INLINED in register_opaque_type({value_type}, members=...).z'Unsupported member type on OpaqueObjectz, member_type=zMember type 'z&' is not supported for this operation.z'Weird method call on TorchScript objectr   zThis particular method call (zn) is not supported (e.g. calling `__setattr__`). Most method calls to TorchScript objects should be supported.zAvoid calling this method.)builderr   rn   r>   r   r   r   rj   r   r   r   r   r   r   create_proxyr   r   rg   rh   rX   rI   r{   r   anypytreetree_leavesr   rr   )rC   r[   r\   r,   r-   r   r   
value_typer   
proxy_argsproxy_kwargsr   x
args_constr   r   kwargs_constr   constant_vals                      r2   r   %TorchScriptObjectVariable.call_methodC  s    	+4::233JJ((9
 9
 zz**HhJ)K "X$XJgdV<"*4&0` a$TF*cd	 j000+<T+J(
		..!**2z2'	 /  %88
 3 33))*mTJV! U#-#6#6"77O P$r 	 ?CCd224d
CFLllnUnda#7#7#9 9nU 0=(J7,7#O%zB\B #//=   " y"6zlBRSWRXXY ZX 0v 6O O ',,R>> E$XJgdV>+W"/}<b c	 	=TZZL	$8/v 6P P -
	
Q DUs   /H4H9c                    > [        [        U R                  R                  5      5      (       a  U R                  R                  $ [        TU ]  5       $ r/   )r   rj   r>   r   rA   rI   )rC   rD   s    r2   rI   ,TorchScriptObjectVariable.as_python_constant  sB    $$%
 
 ::&&&w)++r9   c                 R    [        [        U R                  R                  5      5      $ r/   )r   rj   r>   r   rH   s    r2   rP   ,TorchScriptObjectVariable.is_python_hashable  s!    #$$%
 	
r9   )r   r   rq   r/   )NN)rX   r   r   r   r   r   int__annotations__classmethodrj   r   r   rl   r   r   rp   r   r   rB   rS   r:   r   r   ru   r   r   rI   rP   r   r   r   s   @r2   r   r      s   HJtC)D$DEJTt T T T :>TT T47TKNT	$T T !%#'11 1 	1
  1 1 
1 1"% . &FG
5 G
S G
_ G
G
Z &Fd
#d
 d
 sm	d

 S#Xd
 
d
d
L,C ,
D 
 
r9   r   )>r   r5   rg   collections.abcr   r   r   typingr   r   r   r	   typing_extensionsr
   r|   torch.utils._pytreeutils_pytreer   torch._guardsr   torch._library.opaque_objectr   r   r   r   r   r   torch.fx.proxyr    r   
eval_framer   excr   r   r   rq   r   r   baser   constantr   dictsr   listsr   miscr    user_definedr!   r"   r   r$   r%   r&   r   r:   r<   r   r@   r9   r2   <module>r     s   (   8 8 8 8 '  $ $    !   " E E  % ! & $     H Dt_T]xB (2r6"223 o
 3 o
dx
 9 x
r9   