
    ɯwg5                         d dl Z d dlZd dlZd dlZd dlmZmZ d dlZd dlm	Z	 ddl
mZ 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      Z G d d      Z e       Zy)    N)OptionalUnion)free_symbols   unimplemented)NewCellVariable)ConstantVariable)ClosureVariable)SymNodeVariablec                       e Zd ZdZddZd Zd Zd Zddee	   de
e	ej                  f   fd	Zd
 Zd Zd Zd Zd Zd ZdefdZy)ComptimeVara  
    A ComptimeVar represents a Python value, at some particular point
    in time, in the Python code we are symbolically evaluating with
    torchdynamo.  This must be distinguished from a runtime value, as
    at compile-time there are some properties of the variable we
    do not know (for example, if the ComptimeVar represents a Tensor,
    we only know metadata about the tensor; we do NOT know what the
    actual data in the Tensor is.)
    returnNc                     || _         y N_ComptimeVar__variable)selfvs     [/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py__init__zComptimeVar.__init__$   s	        c                 6    | j                   j                         S )a  
        Returns an fx.Proxy (or tuple/list of fx.Proxy) representing
        this variable in the FX graph we are assembling to pass
        to the user compiler.

        This method only works for variables we actually track in
        the FX graph, aka Tensors (and ints, if you are compiling
        with dynamic shapes).  In particular, if you have a list
        or tuple of tensors, you will get a list/tuple of proxies
        (not a single proxy representing the entire list/tuple).
        )r   as_proxyr   s    r   r   zComptimeVar.as_proxy'   s     ''))r   c                 6    | j                   j                         S )z;
        Returns True if as_proxy() would succeed.
        )r   is_proxyr   s    r   r   zComptimeVar.is_proxy5   s     ''))r   c                 d    | j                   j                         j                  j                  d   S )ax  
        Returns a "fake" value (either a FakeTensor or a SymInt)
        representing the variable in question.  This only works
        for variables that denote Tensor or int.  You can use
        this to query metadata; e.g., v.as_fake().size(0) will
        tell you the compile-time known size of the tensor.

        WARNING: Do NOT mutate the returned tensor.
        example_value)r   r   nodemetar   s    r   as_fakezComptimeVar.as_fake;   s(     '')..33ODDr   dimc                 @    | j                         j                  |      S )z
        Returns the size of the tensor (if dim is None) or the size
        at the dimension dim.  The returned size may be a SymInt.
        )r"   size)r   r#   s     r   r%   zComptimeVar.sizeG   s    
 ||~""3''r   c                 6    | j                   j                         S )zd
        Returns what type(v) would have returned for the variable
        at compile time.
        )r   python_typer   s    r   r'   zComptimeVar.python_typeN   s    
 **,,r   c                 6    | j                   j                         S )a  
        Returns the Python value this variable would have, but only if it is
        completely known at compile-time (e.g., it is constant).

        WARNING: Do NOT mutate the returned constant.  The returned constant
        may or may not correspond to the actual value this variable may take
        on at runtime; for example, if the variable in question is a constant
        list, we may return a copy of that list.
        )r   as_python_constantr   s    r   r)   zComptimeVar.as_python_constantU   s     1133r   c                 6    | j                   j                         S )zC
        Returns True if as_python_constant would succeed.
        )r   is_python_constantr   s    r   r+   zComptimeVar.is_python_constanta   s     1133r   c                     t        | j                  t              r*t        | j                  j                        }t        |      S y)NF)
isinstancer   r   r   sym_numbool)r   fss     r   
is_dynamiczComptimeVar.is_dynamicg   s0    doo7doo556B8Or   c                     t        | j                  t              r| j                  j                          yt        | j                  t              ryt        d| j                   dt        | j                         d      )zW
        Forces that a value is static, inducing a guard on its specific value
        zcannot force z (z) staticN)r-   r   r   evaluate_exprr
   AssertionErrortyper   s    r   force_staticzComptimeVar.force_staticm   sb     doo7OO))+)9: 043H2IR r   c                     | j                   S )z
        Returns the internal data structure VariableTracker that Dynamo uses
        to represent variables at compile time.  There are no BC guarantees on
        this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if you rely on
        it.
        r   r   s    r   1_i_will_not_complain_if_bc_breaks_VariableTrackerz=ComptimeVar._i_will_not_complain_if_bc_breaks_VariableTracker{   s     r   c                 6    | j                   j                         S r   )r   
debug_reprr   s    r   __repr__zComptimeVar.__repr__   s    ))++r   r   Nr   )__name__
__module____qualname____doc__r   r   r   r"   r   intr   torchSymIntr%   r'   r)   r+   r1   r6   r8   strr;    r   r   r   r      sk    **
E( (sELL7H1I (-
44,# ,r   r   c                       e Zd ZdZddZdddedefdZdd	Zd
 Z	d Z
ddddZd Zd ZdddZddddZddddZddddZddddZdddZd Zd Zy)ComptimeContextz
    This context class provides access to a public API for Dynamo's internals.
    If there is something here you would find useful that is missing, please
    file a feature request at https://github.com/pytorch/pytorch/
    r   Nc                     || _         y r   _ComptimeContext__tx)r   txs     r   r   zComptimeContext.__init__   s	    	r   r   
stacklevelnamec                   | j                  |      }t        |d      r||j                  v r|j                  |   }t        |t              r6t        |j                  j                  j                  |j                           S t        |j                  j                  j                  |            S |j                  |   }t        |t              r.t        |j                  j                  j                  |            S t        |      S )zL
        Retrieve the compile-time known information about a local.
        closure_cells)_ComptimeContext__get_txhasattrrP   r-   r   r   outputroot_txsymbolic_localsrN   side_effects	load_cellr	   )r   rN   rM   rK   cellrs         r   	get_localzComptimeContext.get_local   s     ]]:& 2'DB4D4D,D##D)D$0"299#4#4#D#DTYY#OPP"299#9#9#C#CD#IJJ""4(A!_-"299#9#9#C#CA#FGG"1~%r   c                     t        |       y)z0
        Manually trigger a graph break
        Nr   )r   msgs     r   graph_breakzComptimeContext.graph_break   s     	cr   c                 B    | j                   j                  j                  S )z
        Retrieve the partially constructed FX graph that would be
        passed to the user compiler after compilation.
        )rJ   rS   graphr   s    r   r_   zComptimeContext.graph   s    
 yy%%%r   c                 2    |j                         rJ d       y)zV
        Asserts that the int is static (and not dynamic, per dynamic shapes)
        zKexpected static but got dynamic (run with TORCH_LOGS=dynamic for more info)N)r1   )r   vals     r   assert_staticzComptimeContext.assert_static   s#    
  	YX	Y  r   T)verbosefilec                    t        | j                  j                  j                  j	                  d|      j
                  |       y)z
        Print the partially constructed FX graph that would be passed
        to the user compiler after compilation.
        r   )rc   rd   N)printrJ   rS   r_   python_codesrc)r   rc   rd   s      r   print_graphzComptimeContext.print_graph   s8    
 	II""..vw.GKKRV	
r   c                 @    t        | j                  j                        S r   )rG   rJ   parentr   s    r   rl   zComptimeContext.parent   s    tyy//00r   c                 V    | j                   }t        |      D ]  }|j                  } |S r   )rJ   rangerl   )r   rM   rK   _s       r   __get_txzComptimeContext.__get_tx   s-    YYz" 	AB		r   rf   c                0    t        t        |      |       y )Nrf   )rg   repr)r   ra   rd   s      r   rg   zComptimeContext.print   s    d3id#r   )rd   rM   c                    | j                  |      }t        t        j                  |j                  |j
                  |j                     j                        j                         |       y)z
        Print the current series of opcodes being executed (not including
        parent frames), including where you are in the particular opcode
        stream.
        )current_offsetrf   N)rQ   rg   disBytecodef_codeinstructionsinstruction_pointeroffset)r   rd   rM   rK   s       r   print_disaszComptimeContext.print_disas   sQ     ]]:&LL		!r/E/EFMM ce	
r   c                    | j                  |      }|j                  D ]   }t        d|j                          |       " y)a  
        Print the current Python value stack.  Note that this is NOT the same
        as the traceback; use print_bt() to print that.  Note that at
        stacklevel=0, this will typically be empty, as comptime cannot
        currently be used in an expression context where there would be
        intermediates on the stack.  If you would find this useful, please
        file a bug at https://github.com/pytorch/pytorch/

        NB: Stack grows downwards in our print
        z- rf   N)rQ   stackrg   r:   )r   rd   rM   rK   ss        r   print_value_stackz!ComptimeContext.print_value_stack   s=     ]]:& 	4ABq||~&'d3	4r   c                    | j                  |      }|j                  j                         D ]%  \  }}t        | d|j	                          |       ' y)z
        Print all of the locals available in the current context.
        By default this view is very limited; you can get more information
        about any individual local using get_local().
        z = rf   N)rQ   rU   itemsrg   r:   )r   rd   rM   rK   kr   s         r   print_localszComptimeContext.print_locals   sP     ]]:&&&,,. 	8DAqQCs1<<>*+$7	8r   c          	      ,   g }| j                  |      }|/|j                  |j                                t        |dd      }|/t	        dj                  t        j                  j                  t        |            j                               |       y)a  
        Print the user code backtrace, starting at the beginning of the
        frame Dynamo started evaluating.  Note that this MAY NOT go all
        the way to the torch.compile invocation, as we may have done
        a graph break and are compiling an intermediate frame as the
        starting point.  If you think the other behavior would be better,
        file a bug at https://github.com/pytorch/pytorch/
        Nrl    rf   )rQ   appendframe_summarygetattrrg   join	tracebackStackSummary	from_listreversedformat)r   rd   rM   r}   rK   s        r   print_btzComptimeContext.print_bt   s}     ]]:&nLL))+,Xt,B n 	GGI**44Xe_ELLNO	
r   c                    t        dj                  d t        | j                  j                  j
                        D              |       y)z
        Print the currently installed guards for the Dynamo context.
        This does NOT include guards associated with variables that
        may or may not be installed in the future if those variables
        are used.
        
c              3   4   K   | ]  }t        |         y wr   )rr   ).0guards     r   	<genexpr>z/ComptimeContext.print_guards.<locals>.<genexpr>  s     T5e&Ts   rf   N)rg   r   sortedrJ   rS   guards)r   rd   s     r   print_guardszComptimeContext.print_guards  s6     	IITF499;K;K;R;R4STT	
r   c                     | j                   S )a  
        Returns the internal data structure InstructionTranslator that Dynamo
        uses to track state of symbolic evaluation.  There are no BC
        guarantees on this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if
        you rely on it.
        rI   r   s    r   7_i_will_not_complain_if_bc_breaks_InstructionTranslatorzGComptimeContext._i_will_not_complain_if_bc_breaks_InstructionTranslator  s     yyr   c                 .    t        j                  |       y r   )timesleep)r   secs     r   r   zComptimeContext.sleep$  s    

3r   r<   )zComptimeContext.graph_break)r=   r>   r?   r@   r   rD   r   rZ   r]   r_   rb   rj   rl   rQ   rg   r{   r   r   r   r   r   r   rE   r   r   rG   rG      s     23 &c &{ &(&Y &* 
1 "& $ #'1 
 )- 4 $(A 8  $ 
& $( 
r   rG   c                      e Zd Zed fd       Zed        Zed        Zed        Zeddd       Zeddd	       Z	eddd
       Z
eddd       Zeddd       Zed        Zed        Zed        Zed        Zed        Zy)	_Comptimec                       y r   rE   rE   r   r   <lambda>z_Comptime.<lambda>*  s    r   c                      |        y)zJfn gets called at compile time in TorchDynamo, calls fallback_fn otherwiseNrE   )fnfallback_fns     r   __call__z_Comptime.__call__)  s	     	r   c                      t        d        y )Nc                 "    | j                         S r   )r]   ctxs    r   r   z'_Comptime.graph_break.<locals>.<lambda>2      S__. r   comptimerE   r   r   r]   z_Comptime.graph_break0      ./r   c                 &     t        d  fd       y )Nc                 B    | j                  | j                  d            S )Ne)rg   rZ   r   s    r   r   z!_Comptime.print.<locals>.<lambda>6  s    SYYs}}S'9: r   c                      t               S r   )rg   r   s   r   r   z!_Comptime.print.<locals>.<lambda>6  s    E!H r   r   r   s   `r   rg   z_Comptime.print4  s    :<LMr   c                      t        d        y )Nc                 "    | j                         S r   )rj   r   s    r   r   z'_Comptime.print_graph.<locals>.<lambda>:  r   r   r   rE   r   r   rj   z_Comptime.print_graph8  r   r   r   rL   c                     t        d        y )Nc                 f    | j                  | j                  d      j                         dz         S NrM   r   rL   )r{   rZ   r)   r   s    r   r   z'_Comptime.print_disas.<locals>.<lambda>?  s.    ==6IIKaO (  r   r   rL   s    r   r{   z_Comptime.print_disas<      	
r   c                     t        d        y )Nc                 f    | j                  | j                  d      j                         dz         S r   r   rZ   r)   r   s    r   r   z-_Comptime.print_value_stack.<locals>.<lambda>G  0    --==6IIKaO .  r   r   rL   s    r   r   z_Comptime.print_value_stackD  r   r   c                    t        d        | S )Nc                 f    | j                  | j                  d      j                         dz         S r   r   r   s    r   r   z8_Comptime.print_value_stack_and_return.<locals>.<lambda>R  r   r   r   )r   rM   s     r   print_value_stack_and_returnz&_Comptime.print_value_stack_and_returnO  s    	

 r   c                     t        d        y )Nc                 f    | j                  | j                  d      j                         dz         S r   )r   rZ   r)   r   s    r   r   z(_Comptime.print_locals.<locals>.<lambda>[  s0    ((==6IIKaO )  r   r   rL   s    r   r   z_Comptime.print_localsX  r   r   c                     t        d        y )Nc                 f    | j                  | j                  d      j                         dz         S r   )r   rZ   r)   r   s    r   r   z$_Comptime.print_bt.<locals>.<lambda>c  s.    ==6IIKaO %  r   r   rL   s    r   r   z_Comptime.print_bt`  r   r   c                      t        d        y )Nc                 "    | j                         S r   )r   r   s    r   r   z(_Comptime.print_guards.<locals>.<lambda>j  s    S--/ r   r   rE   r   r   r   z_Comptime.print_guardsh  s    /0r   c                     t        d        y )Nc                 B    | j                  | j                  d            S Nra   )rb   rZ   r   s    r   r   z)_Comptime.assert_static.<locals>.<lambda>n  s    S..s}}U/CD r   r   ra   s    r   rb   z_Comptime.assert_staticl  s    DEr   c                     t        d        y )Nc                 @    | j                  d      j                         S r   )rZ   r6   r   s    r   r   z(_Comptime.force_static.<locals>.<lambda>r  s    S]]51>>@ r   r   r   s    r   r6   z_Comptime.force_staticp  s    @Ar   c                       d } t        |        y)a  
        Like pdb breakpoint(), but drop into pdb whenever this line
        of code is compiled by dynamo.  Use it by putting
        this in your model code::

            from torch._dynamo.comptime import comptime
            comptime.breakpoint()

        And then, inside pdb, you can access 'ctx' to query things
        about the compilation context::

            (Pdb) !ctx.print_bt()
            (Pdb) !ctx.print_locals()
            (Pdb) p ctx.get_local("attention").as_fake()
        c                 L    | j                         }t        j                          y r   )rl   builtins
breakpoint)	inner_ctxr   s     r   innerz#_Comptime.breakpoint.<locals>.inner  s    ""$C!r   Nr   )r   s    r   r   z_Comptime.breakpointt  s    $	" 	r   c                     t        d        y )Nc                 ^    | j                  | j                  d      j                               S )Nr   )r   rZ   r)   r   s    r   r   z!_Comptime.sleep.<locals>.<lambda>  s!    SYYs}}U';'N'N'PQ r   r   )r   s    r   r   z_Comptime.sleep  s    QRr   N)r=   r>   r?   staticmethodr   r]   rg   rj   r{   r   r   r   r   r   rb   r6   r   r   rE   r   r   r   r   (  s2   !-   0 0 N N 0 0 "# 
 
 () 
 
 67   #$ 
 
   
 
 1 1 F F B B  . S Sr   r   )r   ru   r   r   typingr   r   rB   %torch.fx.experimental.symbolic_shapesr   excr   	variablesr	   variables.constantr
   variables.miscr   variables.tensorr   r   rG   r   r   rE   r   r   <module>r      s]     
   "  >  & 0 + -l, l,b[ [|fS fSR ;r   