
    [Th7                         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  SSK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5      r " S S5      r " S S5      r\" 5       rg)a_  
This module provides the public comptime interface to TorchDynamo, enabling users to execute
arbitrary Python code during symbolic evaluation of their programs.

The comptime interface allows inspection and modification of TorchDynamo's compilation
process while it is running. This can be useful for:

- Debugging compilation issues
- Inspecting intermediate state
- Adding custom guards or graph breaks
- Analyzing symbolic shapes and values

Example usage:

    import torch
    from torch._dynamo.comptime import comptime

    def my_model(x):
        # Print the compile-time known information about x
        comptime.print(x)

        # Print the current FX graph being constructed
        comptime.print_graph()

        # Force a value to be treated as static
        if comptime(lambda ctx: ctx.get_local("x").is_dynamic()):
            comptime.force_static(x)

        # Add a manual graph break
        comptime.graph_break()

Note: While this API provides significant flexibility, it intentionally avoids
exposing internal implementation details of TorchDynamo to maintain compatibility
across versions.
    N)OptionalUnion)free_symbols   unimplemented_v2)CellVariable)ConstantVariable)SymNodeVariablec                       \ rS rSrSrSS jrS rS rS rSS	\	\
   S\\
\R                  4   4S
 jjrS rS rS rS rS rS rS\4S jrSrg)ComptimeVar6   a  
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                     Xl         g N_ComptimeVar__variable)selfvs     N/var/www/auris/envauris/lib/python3.13/site-packages/torch/_dynamo/comptime.py__init__ComptimeVar.__init__A   s        c                 6    U R                   R                  5       $ )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   ComptimeVar.as_proxyD   s     ''))r   c                 6    U R                   R                  5       $ )z+
Returns True if as_proxy() would succeed.
)r   is_proxyr   s    r   r   ComptimeVar.is_proxyR   s     ''))r   c                 d    U R                   R                  5       R                  R                  S   $ )a@  
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_fakeComptimeVar.as_fakeX   s(     '')..33ODDr   dimc                 @    U R                  5       R                  U5      $ )zw
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)   ComptimeVar.sized   s    
 ||~""3''r   c                 6    U R                   R                  5       $ )zL
Returns what type(v) would have returned for the variable
at compile time.
)r   python_typer   s    r   r,   ComptimeVar.python_typek   s    
 **,,r   c                 6    U R                   R                  5       $ )ay  
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/   ComptimeVar.as_python_constantr   s     1133r   c                 6    U R                   R                  5       $ )z3
Returns True if as_python_constant would succeed.
)r   is_python_constantr   s    r   r2   ComptimeVar.is_python_constant~   s     1133r   c                     [        U R                  [        5      (       a*  [        U R                  R                  5      n[        U5      $ g)NF)
isinstancer   r   r   sym_numbool)r   fss     r   
is_dynamicComptimeVar.is_dynamic   s3    doo77doo556B8Or   c                    [        U R                  [        5      (       a  U R                  R                  5         g[        U R                  [        5      (       a  g[        SU R                   S[        U R                  5       S35      e)zG
Forces that a value is static, inducing a guard on its specific value
zcannot force z (z) staticN)r5   r   r   evaluate_exprr
   AssertionErrortyper   s    r   force_staticComptimeVar.force_static   sh     doo77OO))+)9:: 043H2IR r   c                     U R                   $ )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_VariableTracker=ComptimeVar._i_will_not_complain_if_bc_breaks_VariableTracker   s     r   c                 6    U R                   R                  5       $ r   )r   
debug_reprr   s    r   __repr__ComptimeVar.__repr__   s    ))++r   )
__variabler   Nr   )__name__
__module____qualname____firstlineno____doc__r   r   r   r%   r   intr   torchSymIntr)   r,   r/   r2   r9   r?   rB   strrF   __static_attributes__ r   r   r   r   6   sk    **
E( (sELL7H1I (-
44,# ,r   r   c                       \ rS rSrSrSS jrSS.S\S\4S	 jjrSS
 jr	S r
S rSSS.S jrS rS rSS.S jrSSS.S jrSSS.S jrSSS.S jrSSS.S jrSS.S jrS rS rSrg)ComptimeContext   z
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                     Xl         g r   _ComptimeContext__tx)r   txs     r   r   ComptimeContext.__init__   s    	r   r   
stacklevelnamec                    U R                  U5      nUR                  U   n[        U[        5      (       a.  [	        UR
                  R                  R                  U5      5      $ [	        U5      $ )z<
Retrieve the compile-time known information about a local.
)_ComptimeContext__get_txsymbolic_localsr5   r	   r   outputside_effects	load_cell)r   r_   r^   r[   vars        r   	get_localComptimeContext.get_local   s\     ]]:&  & c<((ryy55??DEE3r   c                 $    [        SUSU S3/ S9  g)z 
Manually trigger a graph break
zComptimeContext graph breakz<Manually triggered ComptimeContext graph break with message .)gb_typecontextexplanationhintsNr   )r   msgs     r   graph_breakComptimeContext.graph_break   s$     	1VWZV[[\]		
r   c                 B    U R                   R                  R                  $ )zj
Retrieve the partially constructed FX graph that would be
passed to the user compiler after compilation.
)rZ   rc   graphr   s    r   rs   ComptimeContext.graph   s    
 yy%%%r   c                 <    UR                  5       (       a   S5       eg)zF
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)r9   )r   vals     r   assert_staticComptimeContext.assert_static   s$     >>## 	
Y	
##r   T)verbosefilec                    [        U R                  R                  R                  R	                  SUS9R
                  US9  g)zg
Print the partially constructed FX graph that would be passed
to the user compiler after compilation.
r   )ry   rz   N)printrZ   rc   rs   python_codesrc)r   ry   rz   s      r   print_graphComptimeContext.print_graph   s8    
 	II""..vw.GKKRV	
r   c                 @    [        U R                  R                  5      $ r   )rV   rZ   parentr   s    r   r   ComptimeContext.parent   s    tyy//00r   c                 Z    U R                   n[        U5       H  nUR                  nM     U$ r   )rZ   ranger   )r   r^   r[   _s       r   __get_txComptimeContext.__get_tx   s(    YYz"AB #	r   r|   c                *    [        [        U5      US9  g )Nr|   )r}   repr)r   rv   rz   s      r   r}   ComptimeContext.print   s    d3id#r   )rz   r^   c                    U R                  U5      n[        [        R                  " UR                  UR
                  UR                     R                  S9R                  5       US9  g)z
Print the current series of opcodes being executed (not including
parent frames), including where you are in the particular opcode
stream.
)current_offsetr|   N)ra   r}   disBytecodef_codeinstructionsinstruction_pointeroffset)r   rz   r^   r[   s       r   print_disasComptimeContext.print_disas   sQ     ]]:&LL		!r/E/EFMM ce	
r   c                    U R                  U5      nUR                   H  n[        SUR                  5        3US9  M      g)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- r|   N)ra   stackr}   rE   )r   rz   r^   r[   ss        r   print_value_stack!ComptimeContext.print_value_stack   s8     ]]:&ABq||~&'d3 r   c                    U R                  U5      nUR                  R                  5        H"  u  pE[        U SUR	                  5        3US9  M$     g)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 = r|   N)ra   rb   itemsr}   rE   )r   rz   r^   r[   kr   s         r   print_localsComptimeContext.print_locals  sI     ]]:&&&,,.DAQCs1<<>*+$7 /r   c          	      ,   / nU R                  U5      nUb1  UR                  UR                  5       5        [        USS5      nUb  M1  [	        SR                  [        R                  R                  [        U5      5      R                  5       5      US9  g)ao  
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/
Nr    r|   )ra   appendframe_summarygetattrr}   join	tracebackStackSummary	from_listreversedformat)r   rz   r^   r   r[   s        r   print_btComptimeContext.print_bt  s}     ]]:&nLL))+,Xt,B n 	GGI**44Xe_ELLNO	
r   c                    [        SR                  S [        U R                  R                  R
                  5       5       5      US9  g)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   :   #    U  H  n[        U5       v   M     g 7fr   )r   ).0guards     r   	<genexpr>/ComptimeContext.print_guards.<locals>.<genexpr>2  s     T4S5e&4Ss   r|   N)r}   r   sortedrZ   rc   guards)r   rz   s     r   print_guardsComptimeContext.print_guards(  s6     	IITF499;K;K;R;R4STT	
r   c                     U R                   $ )z
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.
rY   r   s    r   7_i_will_not_complain_if_bc_breaks_InstructionTranslatorGComptimeContext._i_will_not_complain_if_bc_breaks_InstructionTranslator6  s     yyr   c                 0    [         R                  " U5        g r   )timesleep)r   secs     r   r   ComptimeContext.sleep?  s    

3r   )__txrI   )zComptimeContext.graph_break)rJ   rK   rL   rM   rN   r   rR   r   rg   rp   rs   rw   r   r   ra   r}   r   r   r   r   r   r   r   rS   rT   r   r   rV   rV      s     23  c  {  	
&
 &* 
1 "& $ #'1 
 )- 4 $(A 8  $ 
& $( 
r   rV   c                   $   \ rS rSr\S 4S j5       r\S 5       r\S 5       r\S 5       r\SS.S	 j5       r	\SS.S
 j5       r
\SS.S j5       r\SS.S j5       r\SS.S j5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       rSrg)	_ComptimeiC  c                      g r   rT   rT   r   r   <lambda>_Comptime.<lambda>E  s    r   c                     U" 5         g)zJfn gets called at compile time in TorchDynamo, calls fallback_fn otherwiseNrT   )fnfallback_fns     r   __call___Comptime.__call__D  s	     	r   c                      [        S 5        g )Nc                 "    U R                  5       $ r   )rp   ctxs    r   r   '_Comptime.graph_break.<locals>.<lambda>M      S__.r   comptimerT   r   r   rp   _Comptime.graph_breakK      ./r   c                 (   ^  [        S U 4S j5        g )Nc                 B    U R                  U R                  S5      5      $ )Ne)r}   rg   r   s    r   r   !_Comptime.print.<locals>.<lambda>Q  s    SYYs}}S'9:r   c                     > [        T 5      $ r   )r}   r   s   r   r   r   Q  s	    E!Hr   r   r   s   `r   r}   _Comptime.printO  s    :<LMr   c                      [        S 5        g )Nc                 "    U R                  5       $ r   )r   r   s    r   r   '_Comptime.print_graph.<locals>.<lambda>U  r   r   r   rT   r   r   r   _Comptime.print_graphS  r   r   r   r]   c                     [        S 5        g )Nc                 `    U R                  U R                  S5      R                  5       S-   S9$ Nr^   r   r]   )r   rg   r/   r   s    r   r   '_Comptime.print_disas.<locals>.<lambda>Z  s,    ==6IIKaO ( r   r   r]   s    r   r   _Comptime.print_disasW      	
r   c                     [        S 5        g )Nc                 `    U R                  U R                  S5      R                  5       S-   S9$ r   r   rg   r/   r   s    r   r   -_Comptime.print_value_stack.<locals>.<lambda>b  .    --==6IIKaO . r   r   r]   s    r   r   _Comptime.print_value_stack_  r   r   c                    [        S 5        U $ )Nc                 `    U R                  U R                  S5      R                  5       S-   S9$ r   r   r   s    r   r   8_Comptime.print_value_stack_and_return.<locals>.<lambda>m  r   r   r   )r   r^   s     r   print_value_stack_and_return&_Comptime.print_value_stack_and_returnj  s    	

 r   c                     [        S 5        g )Nc                 `    U R                  U R                  S5      R                  5       S-   S9$ r   )r   rg   r/   r   s    r   r   (_Comptime.print_locals.<locals>.<lambda>v  s.    ((==6IIKaO ) r   r   r]   s    r   r   _Comptime.print_localss  r   r   c                     [        S 5        g )Nc                 `    U R                  U R                  S5      R                  5       S-   S9$ r   )r   rg   r/   r   s    r   r   $_Comptime.print_bt.<locals>.<lambda>~  s,    ==6IIKaO % r   r   r]   s    r   r   _Comptime.print_bt{  r   r   c                      [        S 5        g )Nc                 "    U R                  5       $ r   )r   r   s    r   r   (_Comptime.print_guards.<locals>.<lambda>  s    S--/r   r   rT   r   r   r   _Comptime.print_guards  s    /0r   c                     [        S 5        g )Nc                 B    U R                  U R                  S5      5      $ Nrv   )rw   rg   r   s    r   r   )_Comptime.assert_static.<locals>.<lambda>  s    S..s}}U/CDr   r   rv   s    r   rw   _Comptime.assert_static  s    DEr   c                     [        S 5        g )Nc                 @    U R                  S5      R                  5       $ r   )rg   r?   r   s    r   r   (_Comptime.force_static.<locals>.<lambda>  s    S]]51>>@r   r   r  s    r   r?   _Comptime.force_static  s    @Ar   c                       S n [        U 5        g)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                 N    U R                  5       n[        R                  " 5         g r   )r   builtins
breakpoint)	inner_ctxr   s     r   inner#_Comptime.breakpoint.<locals>.inner  s    ""$C!r   Nr   )r  s    r   r  _Comptime.breakpoint  s    &	" 	r   c                     [        S 5        g )Nc                 ^    U R                  U R                  S5      R                  5       5      $ )Nr   )r   rg   r/   r   s    r   r   !_Comptime.sleep.<locals>.<lambda>  s    SYYs}}U';'N'N'PQr   r   )r   s    r   r   _Comptime.sleep  s    QRr   rT   N)rJ   rK   rL   rM   staticmethodr   rp   r}   r   r   r   r   r   r   r   rw   r?   r  r   rS   rT   r   r   r   r   C  s2   !-   0 0 N N 0 0 "# 
 
 () 
 
 67   #$ 
 
   
 
 1 1 F F B B  0 S Sr   r   )rN   r
  r   r   r   typingr   r   rP   %torch.fx.experimental.symbolic_shapesr   excr   	variablesr	   variables.constantr
   variables.tensorr   r   rV   r   r   rT   r   r   <module>r     s`   "H  
   "  > ! # 0 -l, l,bY YxgS gST ;r   