
    ^jL                       d dl mZ d dlZd dlZd dlZd dlmZmZ ddlm	Z	 ddl
mZ ddlmZmZmZ erd d	lmZ d d
lmZ ddlmZ ddlmZ  G d d      Z G d dee      Z G d de      Z G d d      Z	 	 	 	 ddZddZ e        y)    )annotationsN)AnyTYPE_CHECKING   )config)is_function_or_wrapper   )SourceLocationVariableTrackerVariableTrackerMeta)Callable)Self)InstructionTranslatorBaseSymNodeVariablec                       e Zd ZdZddZddZy)	LazyCachez+Container to cache the real VariableTrackerc                    t        |t              s|st        d      || _        || _        d | _        d | _        d | _        y )Nz9source is required for non-LazySymNodeFormatString values)
isinstanceLazySymNodeFormatStringAssertionErrorvaluesource	name_hintsource_locationvt)selfr   r   s      g/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py__init__zLazyCache.__init__   sF    %!89$O  
%)6:*.    c                \   | j                   t        d      ddlm} ddlm} |j                         }t        | j                  t              r,|j                  j                  || j                        | _         n3 |j                  || j                  d      | j                        | _         | j                  %| j                   j                  | j                         | j                   ;| j                   j                   %| j                   j#                  | j                          | `| `| `| `y )Nz0LazyCache.realize() called but vt is already setr   )InstructionTranslatorr	   )builderFallow_lazy_constant)r   r   symbolic_convertr"    r#   
current_txr   r   r   SourcelessBuildercreateVariableBuilderr   r   set_name_hintr   set_source_location)r   r"   r#   txs       r   realizezLazyCache.realize$   s    77 !STT<"--/djj"9://66r4::FDG
g--DKKU . jjDG >>%GG!!$..1+0G0G0OGG''(<(<=JKN r    N)r   r   r   r   returnNoner0   r1   )__name__
__module____qualname____doc__r   r/    r    r   r   r      s    5
/!r    r   c                  .    e Zd ZdZdZdhej                  Zedd	 	 	 	 	 	 	 	 	 dd       Zd fdZ	ddZ
dd	Zdd
ZddZd dZd!dZd"dZd#dZd$dZd%dZd&dZd'dZej,                  ZeZe	 d(dd	 	 	 	 	 	 	 d)d       ZddZd"dZd"dZ xZS )*LazyVariableTrackera  
    A structure that defers the creation of the actual VariableTracker
    for a given underlying value until it is accessed.

    The `realize` function invokes VariableTracker.build() to produce the real object.
    Once a LazyVariableTracker has been realized, internal bookkeeping will
    prevent double realization.

    This object should be utilized for processing containers, or objects that
    reference other objects where we may not want to take on creating all the
    VariableTrackers right away.
    T_cacheN)r.   c               4   t        |       t        j                  v rt        j                  | |fi |S |M|K|sI|j                  j
                  }|j                  |      }||S t        t        | |      |      }|||<   |S t        t        | |      fd|i|S )N)r   r   )	typeLazyConstantVariablesupported_typesr*   outputvariable_tracker_cachegetr9   r   )r   r   r.   optionscachecachedr   s          r   r*   zLazyVariableTracker.createT   s     ;.>>>'..ufHHH >f0II44EYYv&F!$Yuf%=fMBE&MI"9UF#;VFVgVVr    c                    t        |t              s!t        dt        |      j                         t        |   di | || _        y )Nz)_cache must be a LazyCache instance, got r7   )r   r   r   r<   r3   superr   r:   r   r:   kwargs	__class__s      r   r   zLazyVariableTracker.__init__k   sH    &), ;DL<Q<Q;RS  	"6"r    c                    | j                   j                  ;| j                   j                          | j                   j                  t        d      | j                   j                  S )z.Force construction of the real VariableTrackerz"LazyCache.realize() did not set vt)r:   r   r/   r   r   s    r   r/   zLazyVariableTracker.realizes   sH    ;;>>!KK!{{~~%$%IJJ{{~~r    c                J    t         j                  || j                               S )zNCheck isinstance after realizing, used by ImplicitRealizingVariableTrackerMeta)r<   __instancecheck__r/   )r   clss     r   lazy_isinstancez#LazyVariableTracker.lazy_isinstance{   s    %%c4<<>::r    c                    | j                         r7| j                  j                  t        d      | j                  j                  S | S )z4Return the real VariableTracker if it already existsz*is_realized() returned True but vt is None)is_realizedr:   r   r   rK   s    r   unwrapzLazyVariableTracker.unwrap   s;    {{~~%$%QRR;;>>!r    c                2    | j                   j                  d uS N)r:   r   rK   s    r   rQ   zLazyVariableTracker.is_realized   s    {{~~T))r    c                    |j                  d| j                        | j                  urt        d      |j                  d| j                        | j                  ur| j	                          t        j                  | j                         fi |S )Nr:   z8cannot clone LazyVariableTracker with a different _cacher   )rA   r:   r   r   r/   r   clonerR   )r   rH   s     r   rV   zLazyVariableTracker.clone   so    ::h,DKK? J  ::h,DKK?LLN$$T[[]=f==r    c                v    | j                         rt        d      t        | j                  j                        S )Nz=peek_type() called on an already realized LazyVariableTracker)rQ   r   r<   r:   r   rK   s    r   	peek_typezLazyVariableTracker.peek_type   s5     O  DKK%%&&r    c                d    | j                         rt        d      | j                  j                  S )Nz>peek_value() called on an already realized LazyVariableTrackerrQ   r   r:   r   rK   s    r   
peek_valuezLazyVariableTracker.peek_value   s0     P  {{   r    c                    | j                         r&| j                  j                  j                  |       y || j                  _        y rT   )rQ   r:   r   r,   r   )r   names     r   r,   z!LazyVariableTracker.set_name_hint   s0    KKNN((.$(DKK!r    c                    || _         | j                         r&| j                  j                  j	                  |       y || j                  _         y rT   )r   rQ   r:   r   r-   )r   r   s     r   r-   z'LazyVariableTracker.set_source_location   s8    .KKNN..?*9DKK'r    c                    d}| j                         r"|dt        | j                                dz  }|S |d| j                          dz  }|S )NzLazyVariableTracker(z
realized: )zunrealized: )rQ   reprrR   rX   )r   variable_infos     r   __str__zLazyVariableTracker.__str__   s]    .z$t{{}*=)>a@@M  |DNN,<+=Q??Mr    c                6    t        | j                         |      S rT   getattrr/   )r   items     r   __getattr__zLazyVariableTracker.__getattr__   s    t||~t,,r    c                    t         S )a  Return the VariableTracker type to use for builtin handler dispatch.

        For regular LazyVariableTracker (not LazyConstantVariable), we return
        LazyVariableTracker itself so that _make_handler knows it needs to realize
        the arguments before calling the handler. LazyConstantVariable overrides
        this to return ConstantVariable since it can stay lazy.
        )r9   rK   s    r   get_handler_type_for_dispatchz1LazyVariableTracker.get_handler_type_for_dispatch   s
     #"r    Fr$   c          
     
    i t        |      }|v r|   d   S t        |      }t        |t              r=xr t	        |t
              }|r|}n j                  |j                               }nt        |t              rH|}||f|<   |j                  }|j                  }	|D ]!  }
|
|	vs j                  ||
         ||
<   # n|t        u r"|D cg c]  } j                  |       }}nx|t        u rt         fd|D              }nY|t        t        j                  fv r?t        |j!                               D ci c]  \  }}| j                  |       }}}n|}||f|<   |S c c}w c c}}w )zP
        Walk an object and realize all LazyVariableTrackers inside it.
        r   r$   c              3  F   K   | ]  }j                  |         yw)r$   N)realize_all).0vr%   rC   rN   s     r   	<genexpr>z2LazyVariableTracker.realize_all.<locals>.<genexpr>   s)       5>QRs   !)idr<   
issubclassr9   r   r=   rm   r/   r   __dict___nonvar_fieldslisttupledictcollectionsOrderedDictitems)rN   r   rC   r%   idx	value_cls	keep_lazyresult
value_dictnonvarskeyro   ks   ` ``         r   rm   zLazyVariableTracker.realize_all   s    =Ei%<:a= K	i!45+W
5BV0WIMMOU@S )  	?3F %E#JJ**G! g%&)oo"3DW '6 'JsO
 $  5>QRF  %  F 4!8!899 !/Aq 3??1eAT?UUF 
 F e_c
's   E:E?c                    dd| j                         rt        d      | j                  j                  }t	        |t
              rt        fd|D              S  |      S )Nc                |    t        j                  |       xs& t        t        |       t              xs t	        |       S rT   )inspect	isbuiltinrr   r<   r   )r   s    r   _helperz5LazyVariableTracker.is_hashable_lazy.<locals>._helper
  s7     !!%( 1d5k401)%0r    z?is_hashable() called on an already realized LazyVariableTrackerc              3  .   K   | ]  } |        y wrT   r7   )rn   ro   r   s     r   rp   z7LazyVariableTracker.is_hashable_lazy.<locals>.<genexpr>  s     1awqz1s   )r   r   r0   bool)rQ   r   r:   r   r   rv   all)r   r   r   s     @r   is_hashable_lazyz$LazyVariableTracker.is_hashable_lazy  s\    	  Q  !!eU#15111u~r    c                d    | j                         rt        d      | j                  j                  S )NzBoriginal_value() called on an already realized LazyVariableTrackerrZ   rK   s    r   original_valuez"LazyVariableTracker.original_value  s0     T  {{   r    c                d    | j                         rt        d      | j                  j                  S )NzCoriginal_source() called on an already realized LazyVariableTracker)rQ   r   r:   r   rK   s    r   original_sourcez#LazyVariableTracker.original_source#  s0     U  {{!!!r    )
r   r   r   r   r.   z InstructionTranslatorBase | NonerB   r   r0   r   r:   r   rH   r   r0   r1   r0   r   rN   r<   r0   r   )r0   zVariableTracker | Selfr0   r   )rH   r   r0   r   )r0   z	type[Any])r0   r   )r]   strr0   r1   )r   r
   r0   r1   r0   r   )rg   r   r0   r   r0   r<   rT   )r   r   rC   z!dict[int, tuple[Any, Any]] | Noner%   r   r0   r   )r3   r4   r5   r6   _no_implicit_realizer   rt   staticmethodr*   r   r/   rO   rR   rQ   rV   rX   r[   r,   r-   rc   rh   rj   visit__repr__classmethodrm   r   r   r   __classcell__rI   s   @r   r9   r9   B   s     @!?!?@N
 04	WWW -	W
 W 
W W,;*>'!):-# !!EH 48;
 %*;; 1;
 "; 
; ;z*!"r    r9   )	metaclassc                       e Zd ZdZeeeefZdddhe	j                  Z
e	 	 	 	 	 	 	 	 dd       Zd fdZddZd fdZd fd	Zdd
ZddZddZddZd fdZ xZS )r=   az  
    A lazy variable tracker for constants (int, float, bool, str) that defers
    guarding until the value is actually used in a way that requires it.

    This allows constants that are just passed through (e.g., returned without
    being used in control flow or math) to avoid unnecessary recompilation when
    their values change.

    Guards are installed lazily:
    - TYPE_MATCH guard is installed when type-based methods (python_type, is_tensor,
      lazy_isinstance) are called
    - CONSTANT_MATCH guard is installed on full realization (e.g., used in control
      flow or math), which subsumes any TYPE_MATCH guard
    _type_guard_installed_type_guard_ref_handler_typec                   ddl m} ddlm} t	        |       t
        j                  vr"t        dt	        |       j                   d      |t        d       ||      r |j                  | fd|i|S t        t        | |      fd|i|S )	Nr   )is_constant_sourcer	   ConstantVariablezunsupported type z for LazyConstantVariablez0source must not be None for LazyConstantVariabler   )r   r   constantr   r<   r=   r>   r   r3   r*   r   )r   r   rB   r   r   s        r   r*   zLazyConstantVariable.createD  s     	0.;2BBB #DK$8$8#99RS  > !STT f%*#**5KK7KK#IeV$<WVWwWWr    c                P    t        |   |fi | d| _        d | _        d | _        y NF)rF   r   r   r   r   rG   s      r   r   zLazyConstantVariable.__init__[  s-    *6*%*"$(*.r    c                    | j                   s| j                         ryddlm}m} | j
                  t        d      | j
                  j                  |j                        } ||       d| _         || _	        y)zCInstall TYPE_MATCH guard if not already installed and not realized.Nr   GuardBuilderinstall_guardz2source must not be None when installing type guardT)
r   rQ   guardsr   r   r   r   
make_guard
TYPE_MATCHr   )r   r   r   guards       r   _ensure_type_guardz'LazyConstantVariable._ensure_type_guarda  sd    %%)9)9);8;; !UVV&&|'>'>?e%)"$r    c                   | j                         rt        | 	         S ddlm} ddlm}m} ddlm	} | j                  t        d      t        | 	         }t        ||      r| j                  P|j                         }|j                  j                   j"                  j%                  | j                         d| _         || j                  j'                  |j(                               |S )	z/Force construction of the real VariableTracker.r   )TracingContextr   r   r	   r   Nz;source must not be None when realizing LazyConstantVariable)rQ   rF   r/   torch._guardsr   r   r   r   r   r   r   r   r   r   rA   guards_contextdynamo_guardsinnerdiscardr   CONSTANT_MATCH)r   r   r   r   r   r~   tracing_contextrI   s          r   r/   zLazyConstantVariable.realizeo  s    7?$$08.;; M  " f./##/"0"4"4"6..<<BBJJ(( (,$$++001L1LMNr    c                    | j                         rt        | 	         S | j                          | j	                         S )z6Return the Python type without triggering realization.)rQ   rF   python_typer   rX   )r   rI   s    r   r   z LazyConstantVariable.python_type  s6    7&((!~~r    c                $    | j                          y)z&Primitive constants are never tensors.Fr   rK   s    r   	is_tensorzLazyConstantVariable.is_tensor  s    !r    c                $    | j                          yr   r   rK   s    r   is_constant_nonez%LazyConstantVariable.is_constant_none  s    !r    c                Z   | j                         rt        | j                               S | j                         }t        j
                  s!|t        u rt        | j                               S t        j                  s!|t        u rt        | j                               S | j                          y)a  Check if we need to realize to determine the VariableTracker type.

        Returns None if we can determine the type without realization (and installs
        TYPE_MATCH guard). Returns the realized type if realization was needed.

        With specialize_int=False or specialize_float=False, ints/floats may become
        either ConstantVariable or SymNodeVariable, so we must realize to know.
        For bool/str, we always know it will be ConstantVariable.
        N)
rQ   r<   r/   rX   r   specialize_intintspecialize_floatfloatr   )r   
value_types     r   _maybe_realize_for_typez,LazyConstantVariable._maybe_realize_for_type  s     ''^^%
 $$s):''&&:+>'' 	!r    c                    | j                   | j                   S ddlm} | j                         }||n|| _         | j                   S )zReturn the VariableTracker type to use for builtin handler dispatch.

        This allows builtins like isinstance() and type() to find the correct
        handler without triggering full realization of the lazy constant.
        r	   r   )r   r   r   r   )r   r   realized_types      r   rj   z2LazyConstantVariable.get_handler_type_for_dispatch  sN     )%%%.446*6M<L 	 !!!r    c                    ddl m} ddlm} | j	                         rt
        |   |      S t        ||      st        ||      s| j                          y| j                         }|t        ||      S t        ||      S )a  Check isinstance without triggering realization when possible.

        LazyConstantVariable only wraps primitive types (int, float, bool, str)
        which always realize to ConstantVariable, so we can answer isinstance
        checks by checking if the target class is ConstantVariable or a parent.

        However, when specialize_int=False or specialize_float=False, integers
        and floats may realize to SymNodeVariable instead of ConstantVariable,
        so we must fall back to full realization for those cases.
        r	   r   r   F)
r   r   tensorr   rQ   rF   rO   rr   r   r   )r   rN   r   r   r   rI   s        r   rO   z$LazyConstantVariable.lazy_isinstance  s     	/+ 7*3// *C0S:
 ##%446$mS11*C00r    )r   r   r   r   rB   r   r0   r   r   r2   r   r   r   )r0   ztype | Noner   )r3   r4   r5   r6   r   r   r   r   r>   r9   rt   r   r*   r   r   r/   r   r   r   r   rj   rO   r   r   s   @r   r=   r=   ,  s     E4-O 
	+	+	N XXX X 
	X X,/%< 
6""1 1r    r=   c                  (    e Zd Z	 	 	 	 	 	 ddZddZy)r   c                r    ddl m} || _        |j                  d|j	                         z   dz         | _        y )Nr	   r   z{:})r   r   sym_node_varr*   as_python_constantfmt_var)r   sym_node_variablefmt_spec_varr   s       r   r   z LazySymNodeFormatString.__init__  s7     	/-'..<2244s:
r    c                    t         j                  | j                  j                         t        | j                  j                                     S rT   )r   formatr   r   r   evaluate_exprrK   s    r   r   z LazySymNodeFormatString.__repr__  s:    zzLL++-!!//12
 	
r    N)r   r   r   r   r0   r1   r   )r3   r4   r5   r   r   r7   r    r   r   r     s$    
!0
@O
	

r    r   c                p     t        j                  t        t                     	 	 	 	 	 	 	 	 d fd       }|S )Nc                D     t        | j                               |i |S rT   re   )r   argsrH   r]   s      r   realize_and_forwardz8_create_realize_and_forward.<locals>.realize_and_forward  s$     -wt||~t,d=f==r    )r   r9   r   r   rH   r   r0   r   )	functoolswrapsrf   r   )r]   r   s   ` r   _create_realize_and_forwardr     sO     __W_d34>!>*->9<>	> 5>
 r    c                     t         j                  j                         D ]>  \  } }| t        j                  vst	        |      s%t        t        | t        |              @ y rT   )r   rs   rz   r9   callablesetattrr   )r]   r   s     r   	_populater     sO    &//557 Ve*333+T3Nt3TUVr    )r]   r   r0   z.Callable[[LazyVariableTracker, Any, Any], Any]r2   )
__future__r   rx   r   r   typingr   r   r'   r   utilsr   baser
   r   r   collections.abcr   typing_extensionsr   r&   r   r   r   r   r9   r=   r   r   r   r7   r    r   <module>r      s    "    %  * F F (&<'*! *!Zg"/5H g"Tz1. z1z
 
$	
	3	V 
r    