
    `i:1                     R   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mZmZmZm	Z	m
Z
mZ ddlZddlZddlZddlZddlZddlZddlZddlZej         G d d	e                      Zej        d
             Zej        d             Zej        dd            Zej        d             ZdS )   )patched_boxed_run)patched_lazy_format_graph_code)patched_load_by_key_path)patched__exec_with_source    )ListTupleDictUnionCallableOptionalAnyNc                   X    e Zd ZU eed<   eed<    ej        ed          Z	e
ed<   d ZdS )DebuggableHookdump_src_dirlog_bytecodeF)default_factoryinitoptimized_code_and_modulec           	         t          j                    }dd l}	 |j        }|j        j        }|j        j                            |j        j	                  d         }|dk    r|dk    rnP|j
        d         }|j        |k    sJ | j                            ||j        g           ddlm} 	 dd l}|j                            dd	                              d
d	                              dd	                              dd	          }|j                            | j        d| d          }	ddlm}
 ddlm}  |
|	          5  |                    |||	          }|j        }d d d            n# 1 swxY w Y   | j        r/ |
|          5  dd l}t3          j        t6                    5  |                    |t;          |dz   d                     d d d            n# 1 swxY w Y   t3          j        t6                    5  |                    |t;          |dz   d                     d d d            n# 1 swxY w Y   t3          j        t6                    5  |                    |t;          |dz   d                     d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   ddlm} ddl m!} |"                    |           |||<   |S # |tF          f$ r}ddl$m%}  |            }dd l&}tO          d|           |&                    ||           tO          d|           tQ          j)        |*                                           tW          j,                     Y d }~d S d }~ww xY w)Nr   T_compilezconvert_frame.pyframe)DecompilationError._<> z__transformed_code_%s_for_z.py)lock_on_file)
Decompiler)code_to_decompilereference_codefilepath_templatez.original_bytecodewbz.transformed_bytecodez&.decompiled_and_compiled_back_bytecode)orig_code_map)output_codes)StringIOzEThere is a problem when decompiling and compiling the following code:)filezGPlease consider submitting an issue to https://github.com/thuml/depyf .)-sys	_getframeosf_backf_codeco_nameco_filenamesplitpathsepf_localsr   append	f_globalsdepyf.decompilerr   replacejoinr   depyf.explain.utilsr    r!   decompile_and_compile_liker   dill
contextlibsuppress	Exceptiondumpopentorch._dynamo.utilsr&   torch._dynamo.convert_framer'   addSyntaxErrorior(   disprintwarningswarngetvalue	traceback	print_exc)selfcodenew_coder   r,   	code_name	file_namer   	func_namer$   r    r!   !decompiled_and_compiled_back_codefilenamer<   r&   r'   er(   	string_iorG   s                        r/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/depyf/explain/enable_debugging.py__call__zDebuggableHook.__call__   s   				LE,I066rw{CCBGIJ&&98J+J+J	 w'|t####&--tU_.EFFF777777-	"III,,S#66>>sCHHPPQTVYZZbbcfhkllI "!;Y;;;!= != 988888333333 /00 I I4>4Y4Ylt  FJ  ^o4Y  5p  5p1<HI I I I I I I I I I I I I I I   F!\(++ F FKKK $,Y77 U U		$X8L-Ld(S(STTTU U U U U U U U U U U U U U U $,Y77 \ \		(D<S1SUY,Z,Z[[[\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ $,Y77 F F		"CT(U}J}  @D  FE  FE  F  F  FF F F F F F F F F F F F F F FF F F F F F F F F F F F F F F :99999@@@@@@>????CM;<44"K0 		" 		" 		"###### 

IJJJY`ijjjjGGH9G---[bkllllM),,..///!!!!!!!!!		"s   +BK  E-!K -E11K 4E15K J$)(GJ$G!	!J$$G!	%J$(H5)J$5H9	9J$<H9	=J$(JJ$J	J$J	J$K $J((K +J(,*K M4#BM//M4N)__name__
__module____qualname__str__annotations__booldataclassesfieldlistr   r   rY        rX   r   r      sa         %6[%6tRW%X%X%XtXXX:" :" :" :" :"rd   r   c              #      K   t          | |d           }|t          | ||           	 d V  |t          | ||           d S d S # |t          | ||           w w xY w)N)getattrsetattr)parentnamevalue	old_values       rX   patchrl   T   s      d++Ie$$$- FD),,,,, ! 9 FD),,,, !s   A Ac              #      K   dd l }|j        j                            |           }	 d V  |                                 d S # |                                 w xY w)Nr   )torch_dynamoconvert_frameregister_bytecode_hookremove)hookrn   handles      rX   enable_bytecode_hookru   `   sX      LLL](??EEFs   A ATFc              #   ^  K   t          | t                    st          d          ddl}ddl}t          j                    j        dz   }t          j	        t           d| dt          dd           ddlm} |j                            |           s ||            |j                            |           } dd	lm} | |d
<   |j        j        j        |d<   |j        j        j        j        |d<   |j        j        j        j        |d<   d|d<   t=          | |          }t?          |j        j        dt@                    5  t?          |j        j        j        dtB                    5  t?          |j        j"        j#        dtH          j%                  5  tM          |          5  	 dV  d |j'        D             }	|j'        D ]\  }
j(        )                    d          rtU          fd|	D                       r<j(        )                    d          rtU          fd|	D                       rrddl+m,} ddl-m.} ddl/m0}m1}  |          }|sEt          j                    j        dz   }t          j	        t           d| d dt          dd            ||
          }|j        2                    | dj(         d          } |||          } |j3        |           D ]}|4                    |j        j5                  d         }|r|)                    d           s|6                    d!          r;	  |j7        |j        2                    | |                     ~# tp          $ r Y w xY wd"|d<   n# d |j'        D             }	|j'        D ]\  }
j(        )                    d          rtU          fd|	D                       r<j(        )                    d          rtU          fd|	D                       rrddl+m,} ddl-m.} ddl/m0}m1}  |          }|sEt          j                    j        dz   }t          j	        t           d| d dt          dd            ||
          }|j        2                    | dj(         d          } |||          } |j3        |           D ]}|4                    |j        j5                  d         }|r|)                    d           s|6                    d!          r;	  |j7        |j        2                    | |                     ~# tp          $ r Y w xY wd"|d<   w xY w	 ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )#a|  
    A context manager to dump debugging information for torch.compile.
    It should wrap the code that actually triggers the compilation, rather than
    the code that applies ``torch.compile``.

    Example:

    .. code-block:: python

        import torch

        @torch.compile
        def toy_example(a, b):
            x = a / (torch.abs(a) + 1)
            if b.sum() < 0:
                b = b * -1
            return x * b

        def main():
            for _ in range(100):
                toy_example(torch.randn(10), torch.randn(10))

        if __name__ == "__main__":
            # main()
            # surround the code you want to run inside `with depyf.prepare_debug`
            import depyf
            with depyf.prepare_debug("./dump_src_dir"):
                main()

    After running the code, you will find the dumped information in the directory ``dump_src_dir``. The details are organized into the following:

    - ``full_code_for_xxx.py`` for each function using torch.compile
    - ``__transformed_code_for_xxx.py`` for Python code associated with each graph.
    - ``__transformed_code_for_xxx.py.xxx_bytecode`` for Python bytecode, dumped code object, can be loaded via ``dill.load(open("/path/to/file", "wb"))``. Note that the load function might import some modules like transformers. Make sure you have these modules installed.
    - ``__compiled_fn_xxx.py`` for each computation graph and its optimization:
        - ``Captured Graph``: a plain forward computation graph
        - ``Joint Graph``: joint forward-backward graph from AOTAutograd
        - ``Forward Graph``: forward graph from AOTAutograd
        - ``Backward Graph``: backward graph from AOTAutograd
        - ``kernel xxx``: compiled CPU/GPU kernel wrapper from Inductor.

    Arguments:

    - ``dump_src_dir``: the directory to dump the source code.
    - ``clean_wild_fx_code``: whether to clean the wild fx code that are not recognized for parts of compiled functions. They are usually used by PyTorch internally.
    - ``log_bytecode``: whether to log bytecode (original bytecode, transformed bytecode from Dynamo, and decompiled_and_compiled_back_code).
    zYou are using an obsolete usage style`depyf.prepare_debug(func=function, dump_src_dir="/path")`. Please use `depyf.prepare_debug(dump_src_dir="/path")` instead, which will automatically capture all compiled functions.r   Nr   :z|: You are trying to debug `torch.compile`. Please make sure the code runs multiple times to cover all the possible branches. )safe_create_directorydatar   unpatched__exec_with_sourceunpatched_load_by_key_pathunpatched___call__Tis_inside_prepare_debug_exec_with_sourceload_by_key_path__code__c                 (    h | ]}|d          j         S )r   r/   ).0xs     rX   	<setcomp>z prepare_debug.<locals>.<setcomp>   s    \\\qadl\\\rd   
resume_in_c              3   0   K   | ]}d | j         v V  dS )r   Nr   r   ri   rO   s     rX   	<genexpr>z prepare_debug.<locals>.<genexpr>   sW        EA  EAmqEXRVEXEX\`\hEh  EA  EA  EA  EA  EA  EArd   torch_dynamo_resume_in_c              3   0   K   | ]}d | j         v V  dS )r   Nr   r   s     rX   r   z prepare_debug.<locals>.<genexpr>   sc        R[  R[  HLRrlpRrRrvz  wC  SC  R[  R[  R[  R[  R[  R[rd   )dump_src)write_code_to_file_template)innermost_fn_debug_get_cache_entry_listz: Code object z is compiled but does not have any compiled cache entries. Probably some torch.nn.Module instances are destroyed too early. It is recommended to make sure the torch.nn.Module instances exist after `with depyf.prepare_debug`.full_code_for_z_%s.pyr   fx_graph_codez.lockF)9
isinstancer]   RuntimeErrorr,   rn   inspectcurrentframef_linenorI   warn_explicit__file__UserWarningdepyf.utilsry   r2   existsabspathglobal_variablesr{   fxgraph_moduler   	_inductor	codecachePyCodeCacher   ro   
eval_frameOptimizeContextrY   r   rl   r   r   utilslazy_format_graph_coder   r   ru   r   r/   
startswithanydepyf.explainr   r:   r   torch._dynamo.eval_framer   r   r9   listdirr1   r3   endswithrr   OSError)r   clean_wild_fx_coder   r,   rn   current_line_numberry   r{   bytecode_hook
code_namesmoduler   r   r   r   entriesfull_srcr$   full_code_pathr)   ri   rO   s                        @rX   prepare_debugr   j   s	     d lC(( |  {  |  |  	|IIILLL!.009A=h  {  {)<  {  {  {  }H  JL  NO  P  P  P1111117>>,'' ,l+++7??<00L&&&&&&'D*/(*?*QD	&').)B)N)_D	%&!&!9!I!RD	&*D	"#"<>>M 
ux$&9;T	U	U +8 +8%/+79KMeff+8 +8%-%<jJhJqrr+8 +8 "-00 !	8 !	8 8 ]\M4[\\\
$1$K ^ ^LD&|..|<< !  EA  EA  EA  EAu  EA  EA  EA  BA  BA ! |../HII !c  R[  R[  R[  R[  PZ  R[  R[  R[  O[  O[ ! 666666OOOOOObbbbbbbb99$??G" \.5.B.D.D.MPQ.Q+ .(  0G  0G=P  0G  0G`d  0G  0G  0G  IT  VX  Z[  \  \  \'xf55H(*\ChTXT`ChChCh(i(i%%@%@K\%]%]NN&BJ|44 ! !D::bgk2226D* !t/O/O !TXTaTabiTjTj !!%BIbgll<&F&FGGGG& ! ! ! D!	! 38.//9 ]\M4[\\\
$1$K ^ ^LD&|..|<< !  EA  EA  EA  EAu  EA  EA  EA  BA  BA ! |../HII !c  R[  R[  R[  R[  PZ  R[  R[  R[  O[  O[ ! 666666OOOOOObbbbbbbb99$??G" \.5.B.D.D.MPQ.Q+ .(  0G  0G=P  0G  0G`d  0G  0G  0G  IT  VX  Z[  \  \  \'xf55H(*\ChTXT`ChChCh(i(i%%@%@K\%]%]NN&BJ|44 ! !D::bgk2226D* !t/O/O !TXTaTabiTjTj !!%BIbgll<&F&FGGGG& ! ! ! D!	! 38./7777/C!	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8 !	8+8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8 +8s   =&V"#+V
U3U	 M8$FU	6)M 
U	 
M-*U	,M--U	8FU)T54U5
U?UU
UU	U3U  U3#U $U3'V
3U77V
:U7;V
>V"
V	V"V	V""V&)V&c               #     K   ddl m}  | d         rt          d          | d         }ddl}|j        j        j                            d          }t          |j	        j
        j        d	t          j                  5  	 d
| d}t          |           t                       dV  |j        j        j                            |           n)# |j        j        j                            |           w xY w	 ddd           dS # 1 swxY w Y   dS )a  
    A context manager to debug the compiled code. Essentially, it sets a breakpoint to pause the program and allows you to check the full source code in files with prefix ``full_code_for_`` in the ``dump_src_dir`` argument of :func:`depyf.prepare_debug`, and set breakpoints in their separate ``__transformed_code_`` files according to the function name. Then continue your debugging.
    r   rz   r   z:You cannot use `depyf.debug` inside `depyf.prepare_debug`.r   r   NFr   z`depyf` places a breakpoint here to pause the program. You can check the full source code in files with prefix `full_code_for_` in zq first, and set breakpoints in their separate files according to the function name. Then continue your debugging.)r   r{   r   rn   _Cro   r   set_eval_framerl   r   Interpreter	boxed_runr   r   rH   
breakpoint)r{   r   rn   callbackmsgs        rX   debugr      s     
 '&&&&&%& YWXXX'LLLL x*99%@@H 
ux#-z;L;U	V	V A A	A X  Ye  X  X  XC#JJJLLLEEEH'66x@@@@EH'66x@@@@@A A A A A A A A A A A A A A A A A As*   :C?<'C#%C?&C..C??DD)TF)r   r   r   r   typingr   r	   r
   r   r   r   r   r=   rI   rL   r`   	itertoolsr*   r,   r   	dataclassobjectr   contextmanagerrl   ru   r   r   rc   rd   rX   <module>r      s   0 0 0 0 0 0 J J J J J J > > > > > > @ @ @ @ @ @ D D D D D D D D D D D D D D D D D D                  



 				  ?" ?" ?" ?" ?"V ?" ?" ?"B - - -    w8 w8 w8 w8r A A A A Ard   