
    3jOS                        S r SSKrSSK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  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  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(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K3J4r4  SSK5J6r6  SSK7J8r8J9r9  \(       a  SSK:J;r;  \" S5      r<\" S5      r=S\>S\\\<\=4   /\\<\=4   4   4S jr? " S S\95      r@ " S S \85      rAg)!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TYPE_CHECKINGTypeVar)	ParamSpec)Source)FakeScriptObject)get_member_typeis_opaque_reference_typeis_opaque_typeis_opaque_value_type
MemberTypeshould_hoist)Proxy   )graph_break_hints)	skip_code)raise_observed_exception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      _/home/wildlama/miniconda3/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_errorH   s9    <4*6** <-aee4!;<s    
0+0)	functoolswrapsr&   r-   r.   r'   )r+   r4   s   ` r3   deco._raise_hard_error_if_graph_break.<locals>.decoG   sC    			<RWW 	<		 	<b 	< 
	< )(    )r   r&   r'   )r(   r8   s     r3    _raise_hard_error_if_graph_breakr;   D   s.    )"b&! )hr2v&6 ) Kr:   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\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$ )OpaqueObjectClassVariableT   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                    > [        U[        5      (       a*  [        U[        R                  5      (       a   SU S35       e[
        TU ]  " S0 UD6  Xl        g )NzEnum class zC should use UserDefinedClassVariable, not OpaqueObjectClassVariable )
isinstancetype
issubclassenumEnumsuper__init__r?   )selfr?   r.   	__class__s      r3   rH   "OpaqueObjectClassVariable.__init__\   sU    ud++
5$))0L0L 	
% !, ,	
M 	"6"
r:   c                     U R                   $ r0   r?   rI   s    r3   as_python_constant,OpaqueObjectClassVariable.as_python_constantd       zzr:   c                     g)NFrA   rN   s    r3   is_python_constant,OpaqueObjectClassVariable.is_python_constantg   s     r:   c                 ,    [        U R                  5      $ r0   )r   r?   rN   s    r3   is_python_hashable,OpaqueObjectClassVariable.is_python_hashablem   s    #DJJ//r:   c                 ,    [        U R                  5      $ r0   )hashr?   rN   s    r3   get_python_hash)OpaqueObjectClassVariable.get_python_hashp   s    DJJr:   c                     U R                   $ r0   rM   rN   s    r3   as_proxy"OpaqueObjectClassVariable.as_proxys   rQ   r:   c                 N    U R                   R                   SU R                   S3$ N())rJ   __name__r?   rN   s    r3   __repr__"OpaqueObjectClassVariable.__repr__v   s$    ..))*!DJJ<q99r:   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O[        US
5      (       a  [        [        U5      R                  R                  S
5      [        R                  5      (       d  [        U R                  U5      nO=[        U5      R                   n[	        SSU R                   SU SU 3SU SU S3SS/S	9  ["        R$                  " U5      (       a  [&        R(                  " X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__z&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   rC   rB   staticmethodrp   propertyhasattr__dict__gettypesFunctionTypegetattrrc   r   
is_literalr   buildsourcer   )rI   rf   rg   obj	type_namer~   s         r3   var_getattr%OpaqueObjectClassVariable.var_getattry   s   
	((T:C c<((++djj)CX&&++dDJJ/CS)$$d3i0044Y?ASASTTdjj$/ I..	D$TZZLv]9+V"1$7RS\R]]v wb[	 &&s++"((1126++DKK.4$$Rf55E  	= GD6:-dV3TUYU_U_T``abtf$>tDJJ?O>PPQR		s   !F AG54G5r-   c           
         [        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[        R                  " X5      U_M     snn5      n[        U R                  5      (       aX  UR                  R                  R                  R!                  5          UR#                  5       nUR#                  5       n	S S S 5        O UR#                  5       nUR#                  5       n	U R                  " W0 W	D6n
[%        S U 5       5      n['        [)        U
5      5      (       a  U
nO>[*        R,                  R.                  R1                  UR                  R2                  U
5      n[4        R7                  U
UX4US9$ s  snnf ! , (       d  f       N= f)	Nz:An opaque object was created in the middle of the program.Opaque object type: rj   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.rk   c              3   <   #    U  H  n[        US S5      v   M     g7f)r~   N)r{   ).0as     r3   	<genexpr>:OpaqueObjectClassVariable.call_function.<locals>.<genexpr>   s      JTHd!;!;Ts   ctor_arg_sources)r   r?   r   rH   __code__r   r    listr   itemsr   r}   r   outputtracing_contextguards_contextskip_guard_installrO   tupler   rC   torch_libraryfake_class_registrymaybe_to_fake_obj	fake_modeTorchScriptObjectVariablecreate)rI   rf   r-   r.   var_argskv
var_kwargsconstant_argsconstant_kwargs
opaque_objr   fake_script_objs                r3   call_function'OpaqueObjectClassVariable.call_function   s    $DJJ//djj))223T.tzzl!<RM !d,&9?H_""2)1,H

 

##**99LLN ( ; ; =","?"?"A ON %779M(;;=OZZ
-

 ! JT JJZ 011(O#nn@@RR		##ZO )//,-	 0 
 	
1 I ONs   #G
>!G##
G1rM   )rc   
__module____qualname____firstlineno____doc__r   rH   rO   boolrS   rV   intrZ   r]   strrd   r   r   r   dictr   __static_attributes____classcell__rJ   s   @r3   r=   r=   T   s    c S T C D 0D 0   # :# :&65 &6S &6_ &6P8
#8
 '8
 S/)*	8

 
8
 8
r:   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-  S\SS 4S jj5       r   S#S\S\S	\S\S-  S
\\S-  S4   S-  S\SS4U 4S jjjrS\4S jrS\4S jr\r\" S5      SSS\S\4U 4S jj5       r      S$S j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\4S jrS\ S\
4S jr!S\4S  jr"S!r#U =r$$ )%r      _fake_script_object_cacheuser_clsr)   c                     [        U[        R                  5      =(       d"    [        U5      =(       d    [        U[        5      $ r0   )rD   r   ScriptObjectr   r   )clsr   s     r3   is_matching_cls)TorchScriptObjectVariable.is_matching_cls   s6     x!3!34 6h'6($45	
r:   Nproxyr?   ctor_args_kwargsr   .optionsc                    [        U[        R                  5      (       a   S[        U5       S35       e[	        XU4SU0UD6n[        U [
        R                  R                  5      (       aV  U R                  R                  S:w  a<  SSK
Jn  UR                  " 5       nUR                  R                  R                  U5        U$ )NzEnum zD should use UserDefinedObjectVariable, not TorchScriptObjectVariabler   placeholderr   r$   )rB   rE   rF   rC   r   r   fxr   nodeoptorch._dynamo.symbolic_convertr%   
current_txr   current_tracerrecord_proxyable_vt)r   r?   r   r   r   outr%   rf   s           r3   r    TorchScriptObjectVariable.create   s     eTYY// 	
DK= de	
/ (*
=M
QX
 eUXX^^,,-1OL&113BII$$88=
r:   r~   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
        XPl        g )Nexample_value)rG   rH   r   rB   r   r   r   r   metar~   r   r   )rI   r   r?   r   r~   r   r.   rJ   s          r3   rH   "TorchScriptObjectVariable.__init__   s`     	)&)
djj%((..1149JJOO  1 !1 !1r:   c                 0   [        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   U R                  S9nUR!                  5       U l        U R                  $ )Nr   r$   r   zCNYI: hoisted opaque objects that accept kwargs, please pass as argsr   )rB   r   r   r   r   r   rC   r   r   r%   r   r   RuntimeErrorr   synthetic_graph_inputr   r]   )rI   r%   rf   
hoisted_vts       r3   r]   "TorchScriptObjectVariable.as_proxy  s    $**ehhnn55 (TZZ(89999D,--P*557 ((+&]   YY<<$))!,%)%:%: = 

 (002
zzr:   c                     [        U R                  [        5      (       a  U R                  R                  OU R                  nU R                  R
                   SU S3$ r`   )rB   r?   r   real_objrJ   rc   )rI   r?   s     r3   __str__!TorchScriptObjectVariable.__str__*  sQ     $**&677 JJ 	
 ..))*!E7!44r:   z<Dynamo cannot safely trace script object due to graph break.rf   r%   rg   c           
        >^ ^^ SSK Jn  SSKJn  T R	                  5       n[        U5      n[        U5      (       Gar  [        UT5      nU[        R                  :X  ag  [        UT5      n[        R                  " U5      (       d  [        U[        R                  5      (       a  [!        UU U4S j5      $ ["        T
T ]I  TT5      $ U[        R&                  :X  at  [        UT5      n[        R                  " U5      (       d  [        U[        R                  5      (       a  T R(                  c  [!        UU U4S j5      $ ["        T
T ]I  TT5      $ [+        U5      (       a  ["        T
T ]I  TT5      $ TS;   a"  [-        UT5      (       d  [/        [0        T5        O[3        SS	U S
T 3ST S3ST S3/S9  [        T R4                  TS 5      n	U	cO  [3        SS	T R4                   ST 3ST R4                   ST S3ST ST R4                   S3/[6        R8                  QS9  [;        U	5      (       d  [3        SS	T R4                   ST 3SS/S9  T R(                  c   eUR=                  U[?        T R(                  T5      T TS9$ )Nr   )call_torchbindr   ) TorchHigherOrderOperatorVariablec                  *   > TR                  TTX5      $ r0   call_methodr-   r.   rg   rI   rf   s     r3   <lambda>7TorchScriptObjectVariable.var_getattr.<locals>.<lambda>G      0@0@T40Xr:   c                  *   > TR                  TTX5      $ r0   r   r   s     r3   r   r   U  r   r:   )__bool____len__:Attempted to access unregistered member on an OpaqueObjectvalue=ri   Member '0' is not registered for this opaque object type.
Register '9' with a MemberType in register_opaque_type(members=...).rk   z.FakeScriptObject missing method implementation	, method=zTorchScript object z doesn't define the method rj   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.)r~   script_obj_varmethod_name) !torch._higher_order_ops.torchbindr   higher_order_opsr   rO   rC   r   r   r   USE_REALr{   rq   ismethodrB   ry   MethodWrapperTyper!   rG   r   INLINEDr~   r   rv   r   rs   r   r?   r   
USER_ERRORcallablemaker   )rI   rf   rg   r   r   r   real_obj_typemember_typer?   methodrJ   s   ```       r3   r   %TorchScriptObjectVariable.var_getattr4  s~    	EF**,X-(()->Kj111$/##E**j522/ / *X  !7.r488
 2 22$/$$U++!%)@)@AAkk) *X  w*2t44%m44w*2t440049P9P
 )< X$XJgdV<"*4&0` a$TF*cd	 T40>H IdV<1$**=XY]X^^_`(.A$**QO&11	 Z IdV<uC	 {{&&&/44dkk40	 5 
 	
r:   c                 4    [         R                  XSU/0 5      $ )N__getitem__)r   r   )rI   rf   keys      r3   mp_subscript_impl+TorchScriptObjectVariable.mp_subscript_impl  s     )44T}seUWXXr:   r-   c           
         SSK Jn  U R                  5       n[        U5      n[	        U5      (       Ga  [        Xr5      n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	 [        R                   " U5       5       5      (       a  [        S
SU SU S3SSU SU S3/S9  ["        R$                  " X5      $ U[        R&                  :X  d  [)        U5      (       a?  [+        X45      u  nnUR,                  R/                  SUU R0                  /UQ7US9nU" UUS9$ [        SSU SU 3SU S3SU S3/S9  [        SSU R2                   SU 3SU S3S /S9  g s  sn	f s  snnf )!Nr   )wrap_fx_proxy__getattr__z3Opaque object with custom __getattr__ not supportedz with custom __getattr__zLDynamo does not support opaque objects types with custom __getattr__ methodsrk   __setattr__c              3   J   #    U  H  n[        [        U5      5      v   M     g 7fr0   )r   rC   )r   rs     r3   r   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.r   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 'z2' with MemberType.INLINED in register_opaque_type(z, members=...).r   )r-   r.   )rf   r   r   r   ri   r   r   r   r   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   rO   rC   r   r   r   r   rq   rr   r   rc   r   r{   anypytreetree_leavesr   r}   r   r   r   r   create_proxyr   r?   )rI   rf   rg   r-   r.   r   r   r   r   x
args_constr   r   kwargs_constr   constant_val
proxy_argsproxy_kwargsr   s                      r3   r   %TorchScriptObjectVariable.call_method  sm    	+**,X-(()->Kj111**=-N  " U#0#9#9"::R S$r 	 ?CCd224d
CFLllnUnda#7#7#9 9nU 0=(J7,7#O%zB\B #//=   " y"6}oEUVZU[[\ ]X 0v 644A?/S ',,R>>
 2 226J7 7 ,=T+J(
L		..!**2z2'	 /  %%88 X$XJgdV<"*4&0` a$TF*cd	 	=TZZL	$8/v 6P P -
	
q DUs   
G68G;c                 R  > [        U R                  [        5      (       a  U R                  R                  $ [	        [        U R                  5      5      (       a  U R                  $ [        U R                  [        R                  5      (       a  U R                  $ [        TU ]%  5       $ r0   )
rB   r?   r   r   r   rC   r   r   rG   rO   )rI   rJ   s    r3   rO   ,TorchScriptObjectVariable.as_python_constant  sr    djj"233::&&&!$tzz"233::

E$6$677::w)++r:   c                 F     U R                  5         g! [         a     gf = f)NTF)rZ   	TypeErrorrN   s    r3   rV   ,TorchScriptObjectVariable.is_python_hashable  s(    	  " 		s    
  c                 8    U R                  5       n[        U5      $ r0   )rO   rY   )rI   r   s     r3   rZ   )TorchScriptObjectVariable.get_python_hash	  s    **,H~r:   otherc                 x    [        U[        5      (       d   eU R                  5       nUR                  5       nX#:H  $ r0   )rB   r   rO   )rI   r  	real_self
real_others       r3   is_python_equal)TorchScriptObjectVariable.is_python_equal  s:    %1111++-	--/
&&r:   c                 "    U R                  5       $ r0   )rO   rN   s    r3   get_real_value(TorchScriptObjectVariable.get_real_value  s    &&((r:   )r   r   r   r~   )NN)NNN)rf   r%   r   r   r)   r   )%rc   r   r   r   r   r   r   __annotations__classmethodrC   r   r   rt   r   r   r   r
   r   rH   r]   r   r   rd   r;   r   r   r   r   r   rO   rV   rZ   objectr  r  r   r   r   s   @r3   r   r      s2   HJtC)D$DEJ
t 
 
 
  !%=A	   s 23d:	
  
% 0 !% $=A11 1 	1
 1  s 23d:1 1 
1 1*% 25 5 H%FR
5 R
S R
_ R
R
hY#Y Y 
	Y &F\
#\
 \
 sm	\

 S#X\
 
\
\
|,C ,D  'V ' ') ) )r:   r   )Br   rE   r6   rq   ry   collections.abcr   r   r   typingr   r   r   typing_extensionsr	   r   torch.utils._pytreeutils_pytreer  torch._guardsr
   "torch._library.fake_class_registryr   torch._library.opaque_objectr   r   r   r   r   r   torch.fx.proxyr    r   
eval_framer   excr   r   r   r   r~   r   r   baser   constantr   dictsr   listsr    miscr!   user_definedr"   r#   r   r%   r&   r'   r   r;   r=   r   rA   r:   r3   <module>r6     s   (     8 8 . . '  $ $   ?  !   "    % ! & $     H Dt_T]xB (2r6"223 E
 3 E
Px) 9 x)r:   