~L if<dZddlZddlZddlZddlZddlmZddlmZm Z m Z m Z m Z ddl Z ddlmZddlmZddlmZddlmZd d lmZd d lmZd d lmZd d lmZGddZGddZGddZ e Z!y)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)Sequence)AnyCallableOptionalTextIOUnion)InstructionTranslatorBase)VariableTracker) FakeTensor) free_symbolsunimplemented_v2) CellVariable)ConstantVariable)SymNodeVariableceZdZdZdeddfdZdeeeeffdZde fdZ dee e jffdZdd eedeee jffd Zdefd Zdefd Zde fd Zde fdZddZdefdZdefdZy) 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.) vreturnNc||_yN_ComptimeVar__variable)selfrs \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py__init__zComptimeVar.__init__Cs c6|jjS)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). )ras_proxyrs rr zComptimeVar.as_proxyFs''))rc6|jjS)z; Returns True if as_proxy() would succeed. )ris_proxyr!s rr#zComptimeVar.is_proxyTs''))rcd|jjjjdS)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)rr nodemetar!s ras_fakezComptimeVar.as_fakeZs('')..33ODDrdimc@|jj|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)rr)s rr+zComptimeVar.sizefs ||~""3''rc6|jjS)zd Returns what type(v) would have returned for the variable at compile time. )r python_typer!s rr-zComptimeVar.python_typems **,,rc6|jjS)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. )ras_python_constantr!s rr/zComptimeVar.as_python_constantts1133rc6|jjS)zC Returns True if as_python_constant would succeed. )ris_python_constantr!s rr1zComptimeVar.is_python_constants1133rct|jtr*t|jj}t |Sy)NF) isinstancerrr sym_numbool)rfss r is_dynamiczComptimeVar.is_dynamics0 doo 7doo556B8Orct|jtr|jjyt|jtryt d|jdt |jd)zW Forces that a value is static, inducing a guard on its specific value z cannot force z (z) staticN)r3rr evaluate_exprrAssertionErrortyper!s r force_staticzComptimeVar.force_staticsb doo 7 OO ) ) + )9 :  043H2IR rc|jS)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. rr!s r1_i_will_not_complain_if_bc_breaks_VariableTrackerz=ComptimeVar._i_will_not_complain_if_bc_breaks_VariableTrackersrc6|jjSr)r debug_reprr!s r__repr__zComptimeVar.__repr__s))++rrrN)__name__ __module__ __qualname____doc__r rrrr r5r#r torchSymIntr(rintr+r;r-rr/r1r7r<r>strrArrrr8s/d *%/1J JK **$* Ez5<<78 E( (sELL7H1I(-T- 4C 44D4 D ?,#,rrceZdZdZdeddfdZddded edefd Z d"d eddfd Z de jjfd ZdeddfdZddddedeeddfdZd#dZd edefdZdddedeeddfdZddddeed eddfdZddddeed eddfdZddddeed eddfdZddddeed eddfdZdddeeddfdZdefdZd eeefddfd!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/ txrNc||_yr_ComptimeContext__tx)rrNs rrzComptimeContext.__init__s  rr stacklevelnamerSc|j|}|j|}t|tr.t |j j j|St |S)zL Retrieve the compile-time known information about a local. )_ComptimeContext__get_txsymbolic_localsr3rroutput side_effects load_cell)rrTrSrNvars r get_localzComptimeContext.get_localsY]]: &  & c< (ryy55??DE E3rmsgc*td|d|dgy)z0 Manually trigger a graph break zComptimeContext graph breakz># Y ##rT)verbosefilerjrkct|jjjj d|j |y)z Print the partially constructed FX graph that would be passed to the user compiler after compilation. r)rjrkN)printrQrXrf python_codesrc)rrjrks r print_graphzComptimeContext.print_graphs8  II   " " . .vw . G K KRV rc@t|jjSr)rMrQparentr!s rrszComptimeContext.parentstyy//00rcV|j}t|D]}|j}|Sr)rQrangers)rrSrN_s r__get_txzComptimeContext.__get_txs- YYz" AB  rrmc0tt||y)Nrm)rnrepr)rrgrks rrnzComptimeContext.prints d3id#r)rkrSc|j|}ttj|j|j |j jj|y)z Print the current series of opcodes being executed (not including parent frames), including where you are in the particular opcode stream. )current_offsetrmN)rVrndisBytecodef_code instructionsinstruction_pointeroffset)rrkrSrNs r print_disaszComptimeContext.print_disassQ]]: & LL !r/E/EFMM ce  rc|j|}|jD] }td|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- rmN)rVstackrnr@)rrkrSrNss rprint_value_stackz!ComptimeContext.print_value_stacks=]]: & 4A Bq||~&'d 3 4rc|j|}|jjD]%\}}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 = rmN)rVrWitemsrnr@)rrkrSrNkrs r print_localszComptimeContext.print_localssP]]: &&&,,. 8DAq QCs1<<>*+$ 7 8rc ,g}|j|}|/|j|jt|dd}|/t dj t jjt|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/ Nrsrm) rVappend frame_summarygetattrrnjoin traceback StackSummary from_listreversedformat)rrkrSrrNs rprint_btzComptimeContext.print_bts} ]]: &n LL))+ ,Xt,Bn  GGI**44Xe_ELLN O rctdjdt|jjj 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.  c34K|]}t|ywr)ry).0guards r z/ComptimeContext.print_guards..<sT5e &TsrmN)rnrsortedrQrXguards)rrks r print_guardszComptimeContext.print_guards2s6  IITF499;K;K;R;R4ST T rc|jS)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. rPr!s r7_i_will_not_complain_if_bc_breaks_InstructionTranslatorzGComptimeContext._i_will_not_complain_if_bc_breaks_InstructionTranslator@syyrsecc.tj|yr)timesleep)rrs rrzComptimeContext.sleepKs  3r)zComptimeContext.graph_break)rrM)!rCrDrErFr rrJrIrr\rdrGfxGraphrfrir5rrrqrsrrVrnrrrrrrrfloatrrKrrrMrMs 49:  c  #  k    s  t  &uxx~~&   "&    -5f-=    133 ;?$$x'7$4$+/! ' z_Comptime.Ssrfn fallback_fnrc|y)zJfn gets called at compile time in TorchDynamo, calls fallback_fn otherwiseNrK)rrs r__call__z_Comptime.__call__Ps  rNctdy)Nc"|jSr)rdctxs rrz'_Comptime.graph_break..\ S__.rcomptimerKrrrdz_Comptime.graph_breakZ ./rec&tdfdy)NcB|j|jdS)Nr)rnr\rs rrz!_Comptime.print..`sSYYs}}S'9:rctSr)rnrsrrz!_Comptime.print..`s E!Hrrrs`rrnz_Comptime.print^s:.drrrrKrrrqz_Comptime.print_graphbrrrrRrSctdy)Ncf|j|jdjdzSNrSr rR)rr\r/rs rrz'_Comptime.print_disas..is.==6IIKaO(rrrRs rrz_Comptime.print_disasf  rctdy)Ncf|j|jdjdzSrrr\r/rs rrz-_Comptime.print_value_stack..q0--==6IIKaO.rrrRs rrz_Comptime.print_value_stacknrrctd|S)Ncf|j|jdjdzSrrrs rrz8_Comptime.print_value_stack_and_return..|rrr)rrSs rprint_value_stack_and_returnz&_Comptime.print_value_stack_and_returnys  rctdy)Ncf|j|jdjdzSr)rr\r/rs rrz(_Comptime.print_locals..s0((==6IIKaO)rrrRs rrz_Comptime.print_localsrrctdy)Ncf|j|jdjdzSr)rr\r/rs rrz$_Comptime.print_bt..s. ==6IIKaO%rrrRs rrz_Comptime.print_btrrctdy)Nc"|jSr)rrs rrz(_Comptime.print_guards..sS--/rrrKrrrz_Comptime.print_guardss /0rrgctdy)NcB|j|jdSNrg)rir\rs rrz)_Comptime.assert_static..sS..s}}U/CDrrrgs rriz_Comptime.assert_statics DErctdy)Nc@|jdjSr)r\r<rs rrz(_Comptime.force_static..sS]]51>>@rrrs rr<z_Comptime.force_statics @Arc2dtddfd}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() inner_ctxrNcL|j}tjyr)rsbuiltins breakpoint)rrs rinnerz#_Comptime.breakpoint..inners""$C    !r)rMr)rs rrz_Comptime.breakpoints& "_ " " rrctdy)Nc^|j|jdjS)Nr)rr\r/rs rrz!_Comptime.sleep..s!SYYs}}U';'N'N'PQrr)rs rrz_Comptime.sleeps QRrrB)rCrDrE staticmethodrrMrrrdrnrqrIrrrrrrrir<rrrrrKrrrrOs*6 o&+ ,b#g& 00NNNN00)* 3 t  /0  T  BCC*+ C   &'  D  11F3F4FFB#B$BB0S5e$SSSrr)"rFrr|rrcollections.abcrtypingrrrrrrGtorch._dynamo.symbolic_convertr torch._dynamo.variables.baser torch._subclasses.fake_tensorr %torch.fx.experimental.symbolic_shapesr excr variablesrvariables.constantrvariables.tensorrrrMrrrKrrrso"H $99 D84>!#0-l,l,bccLjSjSZ ;r