Ë
    g^(hÝ<  ã                   óÆ  — d Z ddlZddlZddlZddlm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  ej.                  e«      Zed„ «       Zd„ Zd„ Zed„ «       Zed„ «       Zed„ «       Z ed¬«      d„ «       Z d„ Z!d„ Z"d8d„Z#de	jH                  jJ                  de&fd„Z'd„ Z(	 	 d9d„Z) ede)¬«        ee!d¬ «      Z* ed!e*¬«       d"„ Z+ ed#e+¬«       d$„ Z, ed%e,¬«       d&„ Z- ed'e-¬«        ee¬(«      Z. ed)e.¬«        G d*„ d+e/«      Z0 G d,„ d-e/«      Z1ed.e	jd                  jf                  fd/„«       Z4ed.e	jd                  jf                  fd0„«       Z5ed.e	jd                  jf                  fd1„«       Z6ed.e	jd                  jf                  fd2„«       Z7ejp                   G d3„ d4«      «       Z9d.e	jd                  jf                  fd5„Z: G d6„ d7«      Z;y):aD  
This module provides debugging backends for TorchDynamo to help diagnose and troubleshoot
compilation and execution issues. It includes:

Key Debugging Backends:
- eager: Simple pass-through backend that runs models in eager mode
- eager_noexcept: Similar to eager but with additional exception handling
- eager_debug: Adds schema validation checks for custom operators
- aot_eager: Uses AOT Autograd with nop compiler for debugging
- aot_eager_decomp_partition: Uses TorchInductor decompositions for debugging
- torchscript: Compiles using TorchScript for debugging JIT-related issues

Testing and Development Tools:
- Backends for inducing specific errors (compile/runtime/accuracy)
- ExplainOutput class for detailed graph compilation analysis
- Utilities for cross-referencing and mode management
- Tools for graph detail inspection and break reason analysis

These backends are primarily used for:
1. Debugging graph breaks and compilation failures
2. Testing error handling and recovery mechanisms
3. Analyzing performance bottlenecks
4. Validating operator schemas and decompositions
é    N)Úimport_module)ÚAnyÚOptional)Ú#min_cut_rematerialization_partition)Ú_guards)Úconfig)Ú
ts_compileé   )Úaot_autograd)Úregister_debug_backendc                 óJ   — |rt         j                  d|«       | j                  S )Nz&eager backend ignoring extra kwargs %s)ÚlogÚwarningÚforward)ÚgmÚfake_tensor_inputsÚkwargss      ú^/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/_dynamo/backends/debugging.pyÚeagerr   /   s   € áÜ�‰Ð<¸fÔEØ�:‰:Ðó    c                 ó   — t        | g«      S ©N)Ú,make_eager_backend_with_torch_function_modes©Úmodes    r   Ú+make_eager_backend_with_torch_function_moder   6   s   € Ü7¸¸Ó?Ð?r   c                 ó"   ‡ ‡— ddl mŠ ˆˆ fd„}|S )zèUsed to trace HOPs (cond and while) for eager exectution, the metadata
    TF mode mutates vars outside of the scope of the HOP, and we can't have graph breaks
    in the HOP, so we need to externally run this mode and not trace it.r   )Ú	ExitStackc                 ó~   •—  ‰«       }‰D ]  }|j                  |«       Œ | j                  }|j                  «        |S r   )Úenter_contextr   Úclose)r   r   r   Ústackr   Úresultr   Úmodess         €€r   Úfnz8make_eager_backend_with_torch_function_modes.<locals>.fn@   s@   ø€ Ù“ˆØò 	&ˆDØ×Ñ Õ%ð	&ð —‘ˆØ�‰ŒØˆr   )Ú
contextlibr   )r$   r%   r   s   ` @r   r   r   :   s   ù€ õ %õð €Ir   c                 óB   ‡ — |rt         j                  d|«       ˆ fd„}|S )Nz/eager_noexcept backend ignoring extra kwargs %sc                  ó†   •— 	  ‰| Ž S # t         $ r/}t        j                  j                  j	                  d«      |‚d }~ww xY w)Nz7Unexpected exception when running generated GraphModule)Ú	ExceptionÚtorchÚ_dynamoÚexcÚTorchDynamoException)ÚargsÚer   s     €r   Úinnerzeager_noexcept.<locals>.innerS   sE   ø€ ð	Ù�t�9ÐøÜò 	Ü—-‘-×#Ñ#×8Ñ8ØIóàðûð	ús   ƒ ˆ	A ‘*;»A )r   r   )r   r   r   r0   s   `   r   Úeager_noexceptr1   L   s!   ø€ áÜ�‰ÐEÀvÔNôð €Lr   c                 óˆ   ‡ — |rt         j                  d|«       ddlm} ˆ fd„}  ||d¬«      |Ž }|j	                  «        |S )Nz3pre_dispatch_eager backend ignoring extra kwargs %sr   )Úmake_fxc                  óZ   •— t        j                  j                  ‰«      j                  | Ž S r   ©r*   ÚfxÚInterpreterÚrun)r.   r   s    €r   Úrunnable_gmz'pre_dispatch_eager.<locals>.runnable_gme   s#   ø€ Ü�x‰x×#Ñ# BÓ'×+Ñ+¨TÐ2Ð2r   T)Úpre_dispatch)r   r   Ú"torch.fx.experimental.proxy_tensorr3   Úprint_readable)r   r   r   r3   r9   Úpre_dispatch_gms   `     r   Úpre_dispatch_eagerr>   ^   sE   ø€ áÜ�‰ÐIÈ6ÔRå:ô3ð >‘g˜k¸Ô=Ð?QÐR€OØ×"Ñ"Ô$àÐr   c                 óR   ‡ ‡— |rt         j                  d|«       ddlmŠ ˆˆ fd„}|S )Nz,eager_debug backend ignoring extra kwargs %sr   )ÚSchemaCheckModec                  ó”   •—  ‰«       5  t        j                  j                  ‰«      j                  | Ž cd d d «       S # 1 sw Y   y xY wr   r5   )r.   r@   r   s    €€r   r0   zeager_debug.<locals>.innerx   s;   ø€ ÙÓñ 	7Ü—8‘8×'Ñ'¨Ó+×/Ñ/°Ð6÷	7÷ 	7ò 	7ús	   ‰+>¾A)r   r   Ú#torch._subclasses.schema_check_moder@   )r   r   r   r0   r@   s   `   @r   Úeager_debugrC   n   s$   ù€ áÜ�‰ÐBÀFÔKåCõ
7ð €Lr   Úts)Únamec                 ó@   — t         j                  j                  | «      S r   )r*   ÚjitÚscript)r   r   s     r   ÚtorchscriptrI      s   € ä�9‰9×Ñ˜BÓÐr   c                 ó    ‡ — ˆ fd„}d|_         |S )Nc                 ó`   •— t         j                  j                  ‰«      j                  | «      S r   ©r*   r6   r7   Ú	boxed_run)r.   Úfx_gs    €r   r8   zboxed_nop.<locals>.run†   s#   ø€ Ü�x‰x×#Ñ# DÓ)×3Ñ3°DÓ9Ð9r   T©Ú_boxed_call)rN   Úexample_inputsr8   s   `  r   Ú	boxed_noprR   …   s   ø€ ô:ð €C„OØ€Jr   c                ó$   ‡ ‡— ˆ ˆfd„}d|_         |S )Nc                 ó�   •— ‰5  t         j                  j                  ‰«      j                  | «      cd d d «       S # 1 sw Y   y xY wr   rL   )r.   rN   r   s    €€r   r8   z boxed_nop_with_mode.<locals>.runŽ   s8   ø€ Øñ 	>Ü—8‘8×'Ñ'¨Ó-×7Ñ7¸Ó=÷	>÷ 	>ò 	>ús	   „.<¼ATrO   )rN   rQ   r   r8   s   ` ` r   Úboxed_nop_with_moderU   �   ó   ù€ õ>ð €C„OØ€Jr   c                 ó$   ‡ ‡— ˆ ˆfd„}d|_         |S )Nc                 óÊ   •— t         j                  j                  ‰«      5  t         j                  j	                  ‰«      j                  | «      cd d d «       S # 1 sw Y   y xY wr   )r*   Ú_subclassesÚCrossRefFakeModer6   r7   rM   )r.   rN   Úignore_op_fns    €€r   r8   z$fake_crossref_boxed_nop.<locals>.run—   sI   ø€ Ü×Ñ×/Ñ/°Ó=ñ 	>Ü—8‘8×'Ñ'¨Ó-×7Ñ7¸Ó=÷	>÷ 	>ò 	>ús   ¡.AÁA"TrO   )rN   rQ   r[   r8   s   ` ` r   Úfake_crossref_boxed_nopr\   –   rV   r   ÚopÚreturnc                 ó   — | j                   dv S )N)ÚatenÚprimsÚprim)Ú	namespace)r]   s    r   Úignore_builtinsrd   Ÿ   s   € Ø�<‰<Ð4Ð4Ð4r   c                  ó@  — t         j                  j                  j                  st        S t         j                  j                  j                  dk(  rt
        S t         j                  j                  j                  dk(  sJ ‚t        j                  t
        t        ¬«      S )NÚallÚ
custom_ops)r[   )	r*   Ú
_functorchr   Úfake_tensor_crossrefrR   r\   Ú	functoolsÚpartialrd   © r   r   Úget_nop_funcrm   £   sq   € Ü×Ñ×"Ñ"×7Ò7ÜÐÜ	×	Ñ	×	 Ñ	 ×	5Ñ	5¸Ò	>Ü&Ð&ä×Ñ×&Ñ&×;Ñ;¸|ÒKÐKÐKÜ× Ñ Ô!8ÄÔWÐWr   c                 óX   —  t        |xs t        |xs t        t        d¬«      | |fi |¤ŽS )NT)Úfw_compilerÚbw_compilerÚpartition_fnÚkeep_inference_input_mutations)r   rR   r   )r   r   ro   rp   r   s        r   Ú	aot_eagerrs   ¯   s@   € ðŒ<ØÒ,¤9ØÒ,¤9Ü8Ø'+ô	ð
 	Ð
ñ(ð
 !'ñ(ð (r   rs   )rE   Úcompiler_fnT)ro   rr   Úaot_eager_default_partitionerc                 ód  — |rt         j                  d|«       ddlm} ddi}|j	                  d«      x}r|j                  |«       t        j                  |«      5   t        t        «       t        «       d„ t        j                  t        d¬	«      ¬
«      | |«      cd d d «       S # 1 sw Y   y xY w)Nz;aot_eager_decomp_partition backend ignoring extra kwargs %sr   )ÚCompilerBisectorÚunlift_effect_tokensTÚaot_eager_decomp_partitionc                  ó4   — t        d«      j                  «       S ©Nztorch._inductor.compile_fx©r   Úselect_decomp_tablerl   r   r   ú<lambda>z,aot_eager_decomp_partition.<locals>.<lambda>à   s   € ¤=Ø,ó$ç!Ñ!Ó#ð r   Úinductor©Úcompiler©ro   rp   Údecompositionsrq   )r   r   Ú!torch._inductor.compiler_bisectorrw   Úget_config_changeÚupdateÚfunctorch_configÚpatchr   rm   rj   rk   r   )r   r   r   rw   Úconfig_patchesÚbisect_changess         r   ry   ry   Ì   s³   € ÙÜ�‰ØIÈ6ô	
õ Cà,¨dÐ3€NØ)×;Ñ;Ø$óð €~ð ð 	×Ñ˜nÔ-ä	×	Ñ	 Ó	/ñ "ð
Œ|ä$›Ü$›ñ$ô #×*Ñ*Ü3¸jôô
ð Ð ó"÷"÷ "ò "ús   ÁA B&Â&B/ry   c           
      óÆ   —  t        t        j                  t        |¬«      t        j                  t        |¬«      d„ t        j                  t        d¬«      ¬«      | |«      S )Nr   c                  ó4   — t        d«      j                  «       S r{   r|   rl   r   r   r~   z6aot_eager_decomp_partition_with_mode.<locals>.<lambda>ö   s   € œ}Ø(ó 
ç
Ñ
Ó
ð r   r   r€   r‚   )r   rj   rk   rU   r   )r   r   r   Úkwargs       r   Ú$aot_eager_decomp_partition_with_moderŽ   ð   s\   € ðŒ<ä×%Ñ%Ô&9ÀÔEÜ×%Ñ%Ô&9ÀÔEñ ô ×&Ñ&Ü/¸*ô
ôð 	Ð
óð r   rŽ   c                 ó¸   — t         j                  sdnt         j                  }t        j                  |¬«      5  t        | |fi |¤Žcd d d «       S # 1 sw Y   y xY w)Nrg   )ri   )r‡   ri   rˆ   ry   )r   r   r   Ú
config_vals       r   Ú#aot_eager_decomp_partition_crossrefr‘     sY   € ô  ×4Ò4ñ 	ä×2Ñ2ð ô
 
×	Ñ	°ZÔ	@ñ LÜ)¨"Ð.@ÑKÀFÑK÷L÷ Lò Lús   ¹AÁAr‘   )ro   Úaot_tsc                   ó   — e Zd Zy)ÚReluCompileErrorN©Ú__name__Ú
__module__Ú__qualname__rl   r   r   r”   r”   "  ó   „ Ør   r”   c                   ó   — e Zd Zy)ÚTestingOnlyCompileErrorNr•   rl   r   r   r›   r›   &  r™   r   r›   r   c                 ó‚   — | j                   j                  D ]%  }|j                  t        j                  k(  sŒ!t
        ‚ | S r   )ÚgraphÚnodesÚtargetr*   Úrelur”   ©r   rQ   Únodes      r   Úrelu_compile_error_TESTING_ONLYr£   *  s6   € à—‘—‘ò #ˆØ�;‰;œ%Ÿ*™*Ó$Ü"Ð"ð#ð €Ir   c                 óÐ   — | j                   j                  D ]<  }|j                  t        j                  k(  sŒ!t        j
                  |_        d|_        Œ> | j                  «        | S )N)FÚReluRuntimeError)r�   rž   rŸ   r*   r    Ú_assertr.   Ú	recompiler¡   s      r   Úrelu_runtime_error_TESTING_ONLYr¨   2  sK   € à—‘—‘ò 4ˆØ�;‰;œ%Ÿ*™*Ó$ÜŸ-™-ˆDŒKØ3ˆD�Ið4ð ‡L�L„NØ€Ir   c                 óî   — | j                   j                  D ]K  }|j                  t        j                  k(  sŒ!t        j
                  |_        |j                  d   df|_        ŒM | j                  «        | S )Nr   r
   )r�   rž   rŸ   r*   r    Úaddr.   r§   r¡   s      r   Ú relu_accuracy_error_TESTING_ONLYr«   <  sX   € à—‘—‘ò *ˆØ�;‰;œ%Ÿ*™*Ó$ÜŸ)™)ˆDŒKØŸ™ 1™ qÐ)ˆD�Ið*ð ‡L�L„Nà€Ir   c                 ó”   — | j                   j                  D ]  }|j                  dk(  sŒ n | S |D ]  }|j                  rŒt        ‚ | S )NÚcall_function)r�   rž   r]   Úis_leafr›   )r   rQ   r¢   Úts       r   Ú#non_leaf_compile_error_TESTING_ONLYr°   G  sT   € ð —‘—‘ò ˆØ�7‰7�oÓ%Ùðð ˆ	Øò *ˆØ�y‹yÜ)Ð)ð*ð €Ir   c                   ó  — e Zd ZU dZeej                  j                     ed<   e	ed<   e	ed<   ee
   ed<   e	ed<   dZeeej                  j                        ed<   dZeeej                         ed	<   dZee   ed
<   defd„Zy)ÚExplainOutputzu
    This is the output of :func:`torch._dynamo.explain()`
    There is no reason to create this class directly.
    ÚgraphsÚgraph_countÚgraph_break_countÚbreak_reasonsÚop_countNÚops_per_graphÚ
out_guardsÚcompile_timesr^   c                 óš  — d| j                   › d�}|d| j                  › d�z  }|d| j                  › d�z  }|dz  }t        | j                  «      D ]C  \  }}|d|dz   › d�z  }|d	|j
                  › d�z  }|d
z  }|j                  D ]  }|d|› d�z  }Œ ŒE | j                  �>|dz  }t        | j                  «      D ]!  \  }}|d|dz   › d�z  }|D ]  }|d|› d�z  }Œ Œ# | j                  �?|dz  }t        | j                  «      D ]"  \  }}|d|dz   › d�z  }|dt        |«      › �z  }Œ$ | j                  �|d| j                  › d�z  }|S )NzGraph Count: ú
zGraph Break Count: z
Op Count: zBreak Reasons:
z  Break Reason r
   z:
z    Reason: z    User Stack:
z      zOps per Graph:
z  Ops z    zOut Guards:
z  Guard zCompile Times: )r´   rµ   r·   Ú	enumerater¶   ÚreasonÚ
user_stackr¸   r¹   Ústrrº   )	ÚselfÚoutputÚidxÚbreak_reasonÚframe_summaryÚopsr]   ÚiÚguards	            r   Ú__str__zExplainOutput.__str__h  sÑ  € Ø  ×!1Ñ!1Ð 2°"Ð5ˆØÐ'¨×(>Ñ(>Ð'?¸rÐBÑBˆØ�J˜tŸ}™}˜o¨RÐ0Ñ0ˆàÐ$Ñ$ˆÜ!*¨4×+=Ñ+=Ó!>ò 	5ÑˆC�Ø˜¨¨a© y°Ð4Ñ4ˆFØ˜ \×%8Ñ%8Ð$9¸Ð<Ñ<ˆFØÐ)Ñ)ˆFØ!-×!8Ñ!8ò 5�Ø˜F = /°Ð4Ñ4‘ñ5ð		5ð ×ÑÐ)ØÐ(Ñ(ˆFÜ% d×&8Ñ&8Ó9ò ,‘��SØ˜F 3¨¡7 )¨3Ð/Ñ/�Øò ,�BØ  R D¨˜mÑ+‘Fñ,ð,ð
 �?‰?Ð&Ø�oÑ%ˆFÜ% d§o¡oÓ6ò .‘��5Ø˜H Q¨¡U G¨3Ð/Ñ/�Ø˜D¤ U£ Ð-Ñ-‘ð.ð ×ÑÐ)Ø˜¨×(:Ñ(:Ð';¸2Ð>Ñ>ˆFØˆr   )r–   r—   r˜   Ú__doc__Úlistr*   r6   ÚGraphModuleÚ__annotations__Úintr   r¸   r   ÚNoder¹   r   ÚGuardrº   rÀ   rÉ   rl   r   r   r²   r²   V  s�   … ñð
 �—‘×%Ñ%Ñ&Ó&ØÓØÓØØñó ð ƒMØ37€M�8˜D §¡§¡Ñ/Ñ0Ó7Ø04€J�˜˜gŸm™mÑ,Ñ-Ó4Ø#'€M�8˜C‘=Ó'ð˜ô r   r²   c                 óV  — |j                  | «       | j                  j                  D �cg c]  }|j                  dk(  sŒ|j                  ‘Œ  }}|t        |«      z  }|j                  |«       | j                  j                  r|j                  | j                  «       | ||||fS c c}w )a¨  
    This function is a utility which processes a torch.fx.GraphModule and
    accumulates information about its ops, graph breaks, and other details. It
    is intended to be used by the ExplainWithBackend class and
    `torch._dynamo.explain()` to provide details from Dynamo's graph capture.

    Parameters:
        gm (torch.fx.GraphModule): The GraphModule to be processed.
        graphs (list): A list that accumulates all the GraphModules processed.
        op_count (int): The total count of operations in all GraphModules processed so far.
        ops_per_graph (list): A list that accumulates the operations of each GraphModule.
        break_reasons (list): A list that accumulates the reasons for breaks in each GraphModule.

    Returns:
        tuple: A tuple containing the processed GraphModule, the updated lists of graphs,
               operations per graph, and break reasons, and the updated operation count.
    r­   )Úappendr�   rž   r]   rŸ   ÚlenÚcompile_subgraph_reasonÚgraph_break)r   r³   r·   r¸   r¶   r¢   rÆ   s          r   Ú_explain_graph_detailrÖ   ‡  s�   € ð( ‡M�M�"ÔØ#%§8¡8§>¡>Ö
P˜4°T·W±WÀÓ5Oˆ4�;‹;Ð
P€CÐ
PØ”�C“Ñ€HØ×Ñ˜ÔØ	×!Ñ!×-Ò-Ø×Ñ˜R×7Ñ7Ô8àˆv�x °Ð=Ð=ùò Qs
   ªB&¿B&c                   óX   — e Zd ZdZdd„Zdej                  j                  fd„Zde	fd„Z
y)	ÚExplainWithBackenda  
    This class is intended to be used as a backend for `torch.compile`. It is
    composable with other backends. When used in this way, it accumulates
    information about graph breaks, ops, and other info and provides a string
    representation summarizing this information.

    Attributes:
        backend (str): The name of the backend to use for optimization.
        graphs (list): A list of the graphs captured by TorchDynamo.
        op_count (int): The total number of operations in all optimized graphs.
        break_reasons (list): A list of graph break reasons with stack traces.

    Example Usage:
        def fn(x):
            x = torch.sigmoid(x)
            return x

        torch._dynamo.reset()
        eb = ExplainWithBackend("inductor")
        optimized_fn = torch.compile(fn, backend=eb)
        result = optimized_fn(torch.randn(5))
        print(eb.output())
    r^   Nc                 óT   — ddl m}  ||«      | _        g | _        d| _        g | _        y )Nr
   )Úlookup_backendr   )ÚregistryrÚ   Úbackendr³   r·   r¶   )rÁ   rÜ   rÚ   s      r   Ú__init__zExplainWithBackend.__init__¾  s'   € Ý,á% gÓ.ˆŒØˆŒØˆŒØˆÕr   r   c                 óª   — t        || j                  | j                  g | j                  «      \  }| _        | _        }| _        | j	                  ||«      S r   )rÖ   r³   r·   r¶   rÜ   )rÁ   r   rQ   Ú_s       r   Ú__call__zExplainWithBackend.__call__Æ  sK   € Ü@UØ�—‘˜TŸ]™]¨B°×0BÑ0BóA
Ñ=ˆˆDŒK˜œ¨¨4Ô+=ð �|‰|˜B Ó/Ð/r   c                 ó�   — t        | j                  «      }t        | j                  ||dz
  | j                  | j                  «      }|S )Nr
   )rÓ   r³   r²   r¶   r·   )rÁ   r´   rÂ   s      r   rÂ   zExplainWithBackend.outputÌ  sB   € Ü˜$Ÿ+™+Ó&ˆÜØ�K‰KØØ˜!‰OØ×ÑØ�M‰Mó
ˆð ˆr   )r^   N)r–   r—   r˜   rÊ   rÝ   r*   r6   rÌ   rà   r²   rÂ   rl   r   r   rØ   rØ   ¥  s.   „ ñó0 ð0˜5Ÿ8™8×/Ñ/ó 0ð
˜ô 
r   rØ   r   )NN)<rÊ   Údataclassesrj   ÚloggingÚ	importlibr   Útypingr   r   r*   Úfunctorch.compiler   r   Útorch._functorchr   r‡   Útorch._functorch.compilersr	   Úcommonr   rÛ   r   Úregister_backendÚ	getLoggerr–   r   r   r   r   r1   r>   rC   rI   rR   rU   r\   Ú_opsÚ
OpOverloadÚboolrd   rm   rs   ru   ry   rŽ   r‘   r’   r)   r”   r›   r6   rÌ   r£   r¨   r«   r°   Ú	dataclassr²   rÖ   rØ   rl   r   r   ú<module>rð      sf  ðñó2 Û Û Ý #ß  ã Ý AÝ Ý 7Ý 1å  Ý @ð €g×Ñ˜Ó!€ð ñó ðò@òð$ ñó ðð" ñó ðð ñó ðñ  �tÔñ ó ð ò
òóð5˜Ÿ
™
×-Ñ-ð 5°$ó 5òXð Øó	(ñ �k¨yÕ 9á ,Ø¸$ô!Ð ñ Ø	(Ð6Sõò"ñ: Ø	%Ð3Mõòñ Ø	/Ø4õò
Lñ Ø	.Ø3õñ 
 *Ô	-€Ù �h¨FÕ 3ô	�yô 	ô	˜iô 	ð ð¨¯©×(<Ñ(<ò ó ðð ð¨¯©×(<Ñ(<ò ó ðð ð¨¯©×)=Ñ)=ò ó ðð ð¨E¯H©H×,@Ñ,@ò ó ðð ×Ñ÷-ð -ó ð-ð`>Ø�‰×Ñó>÷<1ò 1r   