
    VhF                        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mZ d dlm	Z	 d dl
mZmZmZmZ d dlZd dl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  ej4                  e      Z G d	 d
e	      Zdeee e f      dee!e f   de fdZ"de dee ef   dee ef   de fdZ#de de!dee    fdZ$ G d d      Z% G d d      Z&e G d d             Z' G d d      Z( G d dejR                  jT                  jV                        Z,	 d,dd d!d!d"d#ejZ                  j\                  d$e/ed%f   d&eee ef      d'eeee ef   e/e   ee   f      d(e/e d%f   d)e0d*e0defd+Z1y)-    N)	dataclass)IntEnum)AnyCallableOptionalUnion)insert_custom_op_guards)ExportedProgram)_export)*refine_dynamic_shapes_from_suggested_fixesc                   (    e Zd ZdZdZdZdZdefdZy)FailureType            returnc                     | j                   S N)nameselfs    J/home/dcms/DCMS/lib/python3.12/site-packages/torch/export/_draft_export.py__str__zFailureType.__str__   s    yy    N)	__name__
__module____qualname__MISSING_FAKE_KERNELDATA_DEPENDENT_ERRORCONSTRAINT_VIOLATION_ERRORMISMATCHED_FAKE_KERNELstrr    r   r   r   r      s&    !" r   r   stackstr_to_filenamer   c           	      x    d}| D ]$  }|d   |vr|d||d       d|d    d|d    z  }& |d| d	   d
    z  }|S )N filenamez
        File z	, lineno linez, in r   z
            locr$   )r%   r&   resframes       r   prettify_stackr/   !   s    
C aO3 eJ/015=/uU[}oa 	a	a ^E"Ie,-..CJr   r,   localssymbolsc                     dj                  d |j                         D              }d| d}t        d |j                         D              r/dj                  d |j                         D              }|d| dz  }|S )N
c              3   2   K   | ]  \  }}d | d|   yw)z            : Nr$   .0kvs      r   	<genexpr>z(prettify_frame_locals.<locals>.<genexpr>1   s!     MdaL2aS1Ms   z
        Locals:
c              3   $   K   | ]  }|d u 
 y wr   r$   )r7   r9   s     r   r:   z(prettify_frame_locals.<locals>.<genexpr>6   s     
3Q1D=
3s   c              3   8   K   | ]  \  }}|	d| d|   y w)Nz           r5   r$   r6   s      r   r:   z(prettify_frame_locals.<locals>.<genexpr>7   s*      
'+q!!-k!Bqc"
s   
z
        Symbols:
)joinitemsanyvalues)r,   r0   r1   	local_strr-   
symbol_strs         r   prettify_frame_localsrC   .   s     		MfllnMMI
 C 
3'.."2
33YY 
/6}}
 

 	   	 Jr   r)   linenoc                     	 t        |       5 }t        |      D ](  \  }}||dz
  k(  s|j                         c cd d d        S  	 d d d        y # 1 sw Y   y xY w# t        $ r Y y w xY w)Nr   )open	enumeratestripFileNotFoundError)r)   rD   fir*   s        r   get_locrL   A   sx    (^ 	(q$Q< (4
?::<'	( 	((	( 	(   s>   A AA	A AA AA A 	A&%A&c            	       X    e Zd Z	 d
dedeeef   deddfdZdefdZ	dee
ef   defd	Zy)FailureReportfailure_typedataxfailr   Nc                 .    || _         || _        || _        y r   )rO   rP   rQ   )r   rO   rP   rQ   s       r   __init__zFailureReport.__init__M   s     *6$(	 
r   c                 V    d| j                    d| j                   d| j                   dS )NzFailureReport(failure_type=z, xfail=z, data=))rO   rQ   rP   r   s    r   __repr__zFailureReport.__repr__T   s2    ,T->->,?x

|SZ[_[d[dZeefggr   r&   c                    | j                   t        j                  k(  r| j                  d   }d| dS | j                   t        j                  k(  ry| j                  d   rt        di | j                  d   nd}d| j                  d    d| j                  d	    d
t        | j                  d   |       d| d| j                  d    dS | j                   t        j                  k(  r| j                  d   rt        di | j                  d   nd}d| j                  d    d| j                  d    dt        | j                  d   |       d| dt        | j                  d   |       d| j                  d    dS | j                   t        j                  k(  r'| j                  d   }| j                  d   }d| d| dS t        d| j                          ) Nopz#Missing fake kernel.
    torch.ops.z is missing a fake kernel implementation.

    Please refer to https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz for more detailed instructions on how to write a meta implementation.
frame_localsr(   zConstraint violation error.
    The specified input dynamic_shapes spec was found to be incorrect during tracing.
    Specifically, this guard was added: exprz, where symbol_to_sourcesz1.
    This occurred at the following stacktrace: r%   z
:
        a  
    Because of this, we have modified the dynamic shapes structure to be the
    following. You can also use torch.export.Dim.AUTO instead to specify your
    dynamic shapes, and we will automatically infer the dynamism for you.
    ```
    dynamic_shapes = new_dynamic_shapesz	
    ```
zSData dependent error.
    When exporting, we were unable to evaluate the value of `z`.
    This was encountered occurrencesz< times.
    This occurred at the following user stacktrace: 
user_stackz	
        z-
    And the following framework stacktrace: z;

    As a result, it was specialized to a constant (e.g. `resulta9  ` in the 1st occurrence), and asserts were inserted into the graph.

    Please add `torch._check(...)` to the original code to assert this data-dependent assumption.
    Please refer to https://docs.google.com/document/d/1kZ_BbB3JnoLbUZleDT6635dHs88ZVYId8jT-yTFgf3A/edit#heading=h.boi2xurpqa0o for more details.
reasonz&Mismatched fake kernel.
    torch.ops.z has a fake kernel implementation, but it has incorrect behavior, based on the real kernel.
    The reason for the mismatch is: z.

    Please refer to https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz for more detailed instructions on how to write a fake implementation.
zUnknown failure type: r$   )
rO   r   r   rP   r!   rC   r/   r    r"   
ValueError)r   r&   rX   locals_infor`   s        r   printzFailureReport.printW   s4    ? ??4Bd   +"H"HH 99^, &B		.(AB 
))-6):(;8DIINaDbCc d00>tyy?QSb0c/d e		 
 ii 456 7  +"B"BB 99^, &B		.(AB 
>>Bii>O=P Q))M23 455CDIIlD[]l5m4n o		 --;DIIg<NP_-`,a b::>))H:M9N O
 
 +"D"DD4BYYx(Fd %%+H -  5d6G6G5HIJJr   )F)r   r   r   r   dictr#   r   boolrS   rV   intrc   r$   r   r   rN   rN   L   s^    MR!'!/3CH~!FJ!	!h# h:KT#s(^ :K :Kr   rN   c            
       p    e Zd Zdee   deeef   deeeeef   f   fdZ	de
fdZdefdZdefdZdd
Zy	)DraftExportReportfailuresr&   expressions_createdc                 .    || _         || _        || _        y r   )ri   r&   rj   )r   ri   r&   rj   s       r   rS   zDraftExportReport.__init__   s     .6.>Q r   r   c                 n    t        | j                        dk(  xs t        d | j                  D              S )Nr   c              3   4   K   | ]  }|j                     y wr   )rQ   )r7   failures     r   r:   z/DraftExportReport.successful.<locals>.<genexpr>   s      .
%GMM.
s   )lenri   allr   s    r   
successfulzDraftExportReport.successful   s5    4==!Q& 
# .
)-.
 +
 	
r   c                 "    d| j                    dS )NzDraftExportReport(rU   )ri   r   s    r   rV   zDraftExportReport.__repr__   s    #DMM?!44r   c                    d}d}d}| j                         r| d| S | dt        | j                         d}t        | j                        D ],  \  }}||dz    d|j	                  | j
                         d	z  }. ||z  }|S )
Nz[93mz[92mz[0maO  
##############################################################################################
Congratuations: No issues are found during export, and it was able to soundly produce a graph.
You can now change back to torch.export.export()
##############################################################################################
zn
###################################################################################################
WARNING: z issue(s) found during export, and it was not able to soundly produce a graph.
Please follow the instructions to fix the errors.
###################################################################################################

r   z. r3   )rq   ro   ri   rG   rc   r&   )r   WARNING_COLORGREEN_COLOR	END_COLORerrorrK   rn   s          r   r   zDraftExportReport.__str__   s    " 	??#} %
   #O $

dmm
	  $DMM2 	IJAwAwbt/C/C!D ERHHE	Ir   Nc                     t        d      )NzNot implemented yet)NotImplementedErrorr   s    r   apply_suggested_fixesz'DraftExportReport.apply_suggested_fixes   s    !"788r   r   N)r   r   r   listrN   rd   rf   r#   r   rS   re   rq   rV   r   rz   r$   r   r   rh   rh      so    R}%R c3hR "#tCH~"56	R
D 

5# 5 49r   rh   c                   J    e Zd ZU eed<   ee   ed<   eeef   ed<   dZ	e
ed<   y)ExpressionCreatedNode	result_idargument_idsrecordFvisitedN)r   r   r   rf   __annotations__r|   rd   r#   objectr   re   r$   r   r   r~   r~      s*    Ns)fGTr   r~   c                       e Zd ZddZdeeeeef   f   defdZ	deeeeef   f   de
fdZdeeeeef   f   defdZy)		LogRecordr   Nc                      i | _         g | _        y r   )	log_countlogsr   s    r   rS   zLogRecord.__init__   s    )+68	r   elementc                 H   |\  }}|dk(  rt        ||d   f      S |dk(  rt        ||d   |d   f      S |dk(  r#t        |t        j                  |d         f      S |dk(  r#t        |t        j                  |d         f      S t        |t        j                  |      f      S )Nmissing_fake_kernelrX   mismatched_fake_kernelr`   !propagate_real_tensors_provenancer^   create_unbacked_symbol)hashjsondumps)r   r   keyrP   s       r   _hashzLogRecord._hash   s    	T''d4j)**,,d4j$x.9::77djjl);<=>>,,djjl);<=>>S$**T*+,,r   c                     | j                  |      }|| j                  v r| j                  |xx   dz  cc<   yd| j                  |<   | j                  j                  |       y)Nr   FT)r   r   r   append)r   r   
hash_values      r   try_addzLogRecord.try_add   sV    ZZ(
'NN:&!+&%&z"		!r   c                 >    | j                   | j                  |         S r   )r   r   )r   r   s     r   get_log_countzLogRecord.get_log_count   s    ~~djj122r   r{   )r   r   r   rS   tupler#   rd   r   rf   r   re   r   r   r$   r   r   r   r      sv    9-U3S#X#67 -C -uS$sCx.%89 d 3U3S#X+>%? 3C 3r   r   c                   D     e Zd Zd fdZd	dZddZdeddf fdZ xZS )
CaptureStructuredTracer   Nc                    g d| _         t               | _        i | _        i | _        t        j                  d      | _        d| _        t        j                  j                  t        j                  j                  j                        x}rt         | E  |       nmt%        j&                  ddt)        j*                               }t        j,                  j/                  t1        j2                         d|z         }t         | E  |       | j5                  t        j                  j                  j7                  d             y )	N)r#   exported_programr   guard_addedr   r   expression_createdr   ztorch.__traceFz[\\/:*?"<>|]_export_T)trace)specific_log_keysr   
log_recordexpression_created_logssymbol_to_expressionslogging	getLoggerloggerprev_get_dtraceosenvirongettorch_logging	_internalDTRACE_ENV_VARsuperrS   resubgetpassgetuserpathr=   tempfile
gettempdirsetFormatterTorchLogsFormatter)r   root_dirsanitized_username	__class__s      r   rS   zCaptureStructuredTrace.__init__   s    	"
 &/[IK$FH"''8$zz~~enn&>&>&M&MNN8NGX&!#goo>O!Pww||##%..H GX&%..22EEDEQRr   c                    t               | _        i | _        | j                  j                  D cg c]2  }t        |t        j                  j                  j                        r|4 }}|D ]  }| j                  j                  |        | j                  j                  |        t        j                  j                  j                  | _        dt        j                  j                  _        | S c c}w NT)r   r   r   r   handlers
isinstancer   r   r   LazyTraceHandlerremoveHandler
addHandlerGET_DTRACE_STRUCTUREDr   )r   handlerpossible_lazy_trace_handlerss      r   	__enter__z CaptureStructuredTrace.__enter__  s    #+')$
  ;;//(
'5>>#;#;#L#LM (
$ (

 4 	/GKK%%g.	/ 	t$$~~77MM9=  6(
s   7C/c                     t               | _        i | _        | j                  j	                  |        | j
                  t        j                  j                  _	        d| _        y )NF)
r   r   r   r   r   r   r   r   r   r   )r   exc_type	exc_value	tracebacks       r   __exit__zCaptureStructuredTrace.__exit__  sE    #+')$!!$'9=9M9M  6$r   r   c                     |j                   } j                  D ]  }||v s j                  j                  |||   f      s)|dk(  r:t	        ||   d   ||   j                  dg       |       j                  ||   d   <   h|dk(  rBdt        t        gd f   dt        dd f fd t         ,  ||   j                  d	             t         -  |        y )
Nr   r   r   r   	emit_funcsym_node_idr   c                     |y j                   j                  |d       x}r@|j                  s!d|_        |j                  D ]  } | |         | |j                         y y r   )r   r   r   r   r   )r   r   r-   arg_log_expression_createdr   s       r   r   z<CaptureStructuredTrace.emit.<locals>._log_expression_created9  sw      +2 &&*&B&B&F&F +T'  s  
 (+{{26CK/2/?/? %P(?	3(O%P !*#** 5 r   expr_node_id)metadatar   r   r   r~   r   r   r   r   rf   r   emit)r   r   r   r   r   r   s   `   @r   r   zCaptureStructuredTrace.emit%  s    ??)) (	)Ch??**C#+?@22 2$SM+6$SM--nbA" 44$SM+6 ! CC6'/t'<6KN6!6$ 0!GL(3-*;*;N*K GL(Q(	)r   r{   )r   r   )	r   r   r   rS   r   r   r   r   __classcell__)r   s   @r   r   r      s+    S:$%*)3 *)4 *) *)r   r   r$   F)dynamic_shapespreserve_module_call_signaturestrictpre_dispatchmodargs.kwargsr   r   r   r   c                   |xs i }|xs i }t               }t        j                  j                  j	                  dd      5  |5  	 d }t        | ||||||      t        j                  j                  dfd       i }
g }i }i }|j                  j                  D ]  \  }}d }|dk(  r|d   |
|d	   <   |d
k(  r1|j                  j                  ||f      |d<   t         j"                  }nv|dk(  r+|Wt         j$                  }t'        |d         dk(  ry||d<   nF|dk(  rt         j(                  }||f||d   <   n&|dk(  r t         j*                  }||f||d   |d   f<   n|J |j-                  t/        ||              |j0                  j3                         D ]!  \  }}|j4                  s|j6                  ||<   # t9        ||
|      }t;        j<                  t?        |jA                                      d d d        d d d        _!        |jE                         sB|jF                  jH                  }tJ        jM                  dt'        |jN                        |       S tJ        jQ                  d       S # t        j                  j                  j                  $ r3}	t        |	j                  |      }t        | ||||||      Y d }	~	ud }	~	ww xY w# 1 sw Y   xY w# 1 sw Y   xY w)NT)"fake_tensor_propagate_real_tensors*generate_fake_kernels_from_real_mismatches)r   r   r   r   r   c                      t               S r   )r#   )eps   r   <lambda>zdraft_export.<locals>.<lambda>~  s    PSTVPW r   )
payload_fnr#   r   r   r   r]   r   r[   r\   r   rX   r   r`   a  
###################################################################################################
WARNING: %s issue(s) found during export, and it was not able to soundly produce a graph.
To view the report of failures in an html page, please run the command:
    `tlparse %s --export`
Or, you can view the errors in python by inspecting `print(ep._report)`.
###################################################################################################
        aS  
##############################################################################################
Congratuations: No issues are found during export, and it was able to soundly produce a graph.
You can now change back to torch.export.export()
##############################################################################################
    ))r   r   
_functorchconfigpatchr   _dynamoexc	UserErrorr   msgr   dtrace_structuredr   r   r   r   r    r!   ro   r   r"   r   rN   r   r>   r   r   rh   r	   graph_moduler|   keys_reportrq   streamr   logwarningri   info)r   r   r   r   r   r   r   capture_structured_log
new_shapesr   r&   ri   custom_ops_logsrj   log_namelog_contentsrO   r8   r9   reportlog_filenamer   s                        @r   draft_exportr   R  s\    \rF#)rN35				 	 	&	&+/37 
' 
 _O _O	J-)/MB. 	(();(X*,(*  	 :<&<&G&G&L&L 0	"HlL5 3??Q0@@ +55CC|, !  +??]*%*EE|$789Q> 5?1222*>>7C\6RT 2355*AA  Qd!3\(5K LM +++OO  W0	d +BBHHJ 	2DAqyy)*#A&	2 #8_>QR 	 o6J6J6L1MN_O _OB BJ-4499  	
, I 		
 IY }}  ** 	CJ ))/MB		_O _O _O _OsV   K%KI<EK1AK<K%<'K#(KKKKK"	K%%K.r   )2r   r   r   r   r   r   dataclassesr   enumr   typingr   r   r   r   r   torch._logging._internaltorch._logging.structured,torch._export.passes.insert_custom_op_guardsr	   torch.exportr
   torch.export._tracer   torch.export.dynamic_shapesr   r   r   r   r   r|   rd   r#   rf   r/   rC   rL   rN   rh   r~   r   r   r   r   r   nnModuler   re   r   r$   r   r   <module>r     s      	 	  !  1 1     P ( ' R g!' 
$tCH~. 
c3h 
TW 
	38n/3CH~&c 3 8C= EK EKP.9 .9b   3 3Ba)U^^55FF a)N (,J
 NR68J	J
S/J T#s(^$J
 U4S>5:tCy#HIJJ %*#s(OJ J J Jr   