
    ir>                     H   S SK r S SKrS SKrS SKJr  S SKJr  S SKJrJ	r	J
r
Jr  S SKrS SKJrJrJr  S SKJrJrJrJrJrJrJrJrJrJrJrJrJrJrJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'  S\#S\(4S	 jr)S
\%S\*4S jr+S\S\*S\*S\(4S jr,   SS\"S\*S\*S\
\   SS4
S jjr-SS\S\.S\
\   SS4S jjr/S\S\(4S jr0S\Rb                  Rd                  S\Rb                  Rf                  S\(4S jr4S\(S\4S jr5S\Rb                  Rd                  S\Rb                  Rf                  S\(4S jr6g)     N)fields)IntEnum)AnyListOptionalTextIO)ExportErrorExportErrorTypeInternalError)BoolBoolListDelegateCallDouble
DoubleListEValueFrame	FrameListFreeCallIntIntListJumpFalseCall
KernelCallMoveCallNullOptionalTensorListProgram
ScalarTypeStringTensor
TensorListTensorShapeDynamismscalar_typereturnc                    0 [         R                  S_[         R                  S_[         R                  S_[         R                  S_[         R
                  S_[         R                  S_[         R                  S_[         R                  S_[         R                  S	_[         R                  S
_[         R                  S_[         R                  S_[         R                  S_[         R                  S_[         R                  S_[         R                   S_[         R"                  S_[         R$                  S0EnUR'                  U S 5      =n(       d  [)        SU  35      eU$ )Nbtcsilhfdc32c64c128bqi8qui8qi32bf16qui4x2qui2x4zUnrecognized scalar_type: )r   BYTECHARSHORTINTLONGHALFFLOATDOUBLE	COMPLEX32	COMPLEX64
COMPLEX128BOOLQINT8QUINT8QINT32BFLOAT16QUINT4x2QUINT2x4getRuntimeError)r"   type2strrets      \/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/exir/print_program.py_scalar_type_strrN   -   sm    	# 		
 	 	 	# 	3 	e 	e 	v 	 	% 	6 	6  	V!" 	X#$ 	X%H( <<T22C27}EFF
    tensorc                 <    U R                   [        R                  :g  $ N)shape_dynamismr!   STATIC)rP   s    rM   _is_dynamic_shape_tensorrU   H   s      $7$>$>>>rO   evalueshow_meminfomark_dynamic_shape_tensorc                    Sn[        U R                  [        5      (       Ga  U R                  nUR                  S:  a,  [	        U5      (       a   S5       eUS-  nUR
                  b   eOU(       aG  UR                  [        R                  :X  a  US-  nO#UR                  [        R                  :X  a  US-  nUS-  nU(       aJ  UR
                  (       a4  USUR
                  R                   S	UR
                  R                   3-  nOUS
-  nX4R                   [        UR                  5       3-  nGO[        U R                  [        5      (       a+  US-  nU R                  nU[!        UR"                  5      -  nGO\[        U R                  [$        5      (       a+  US-  nU R                  nU[!        UR"                  5      -  nGO[        U R                  [&        5      (       a+  US-  nU R                  nU[!        UR"                  5      -  nGO[        U R                  [(        5      (       a+  US-  nU R                  nU[!        UR"                  5      -  nGO~[        U R                  [*        5      (       a+  US-  nU R                  n	U[!        U	R"                  5      -  nGO4[        U R                  [,        5      (       a  U R                  n
USU
R.                   3-  nO[        U R                  [0        5      (       a  U R                  nUSUR2                   3-  nO[        U R                  [4        5      (       a(  U R                  nUS[7        UR8                  5       3-  nOq[        U R                  [:        5      (       a  U R                  nUSUR<                   3-  nO3[        U R                  [>        5      (       a  US-  nO[A        SU  35      eUS-  nU$ )Nz[34mr   z*A constant tensor can not be dynamic shapeCTUBDUTm.zm.TLOTLILDLBLIDBSNzUnrecognized type of evalue: [0m)!
isinstancevalr   data_buffer_idxrU   allocation_inforS   r!   DYNAMIC_BOUNDDYNAMIC_UNBOUND	memory_idmemory_offsetsizesrN   r"   r    stritemsr   r   r   r   r   int_valr   
double_valr   intbool_valr   
string_valr   rJ   )rV   rW   rX   evstrrP   
tensorlistoptionaltensorlistintlist
doublelistboollistintval	doublevalboolval	stringvals                 rM   _format_evaluer   L   s>    E&**f%%!!A%/  <;<  TME))111(((,?,M,MMTME**.A.Q.QQTMESLE))q!7!7!A!A B!FDZDZDhDhCijjETMELL>"263E3E"F!GHH	FJJ
	+	+ZZ
Z%%&&	FJJ 2	3	3#ZZ'--..	FJJ	(	(**W]]##	FJJ
	+	+ZZ
Z%%&&	FJJ	)	)::X^^$$	FJJ	$	$1V^^$%%	FJJ	'	'JJ	1Y))*++	FJJ	%	%**1S))*+,,	FJJ	'	'JJ	1Y))*++	FJJ	%	%:6(CDD	YELrO   programoutc           	        ^^^^^ U R                   S   nUR                  nUR                  nUR                  S   nUR                  nUR
                  mUR                  mUR                  mS[        S[        4UUUUU4S jjn	[        S[        U5       S3US9  [        U5       GHF  u  p[        U
S S	3S
US9  [        UR                  [        5      (       a  UR                  nX\R                      nUR"                  nUR$                  (       a  UR&                   SUR$                   3OUR&                  nSR)                  [+        X5      5      n[        U SU 3US9  M  [        UR                  [,        5      (       a`  UR                  nUUR.                     nUR"                  nUR0                   nSR)                  [+        X5      5      n[        U SU 3US9  GM<  [        UR                  [2        5      (       a9  UR                  n[        SU	" UR4                  5       SUR6                   3US9  GM  [        UR                  [8        5      (       a?  UR                  n[        SU	" UR:                  5       SU	" UR<                  5       3US9  GM  [        UR                  [>        5      (       a*  [        SU	" UR                  R@                  5       3US9  GM;  [C        SU 35      e   g)aS  
Dump the instruction list of a program in a more human readable fashion.

The dump follows the following BNF syntax (I combime some regex syntax
so the grammar becomes shorter. The grammar is not strict but the main
purpose is to let people understand the dump):
```
  PROGRAM: (INSTRUCTION)+
  INSTRUCTION: SEQUENCE_NO ':' (CALL_KERNEL | JUMP_FALSE)
  JUMP_FALSE: 'JF' '(' EVALUE ')' '->' TARGET_SEQUENCE_NO
  CALL_KERNEL: OVERLOADDED_OP_NAME ARGS
  ARGS: EVALUE | ARGS ',' EVALUE
  EVALUE: EVALUE_IDX ( TENSOR | INT | BOOL | ...)
  INT: 'I' ACTUAL_INT_VALUE
  BOOL: 'B' ZERO_OR_ONE
  CONST_TENSOR_PREFIX: 'CT'
  TENSOR: ('T' | CONST_TENSOR_PREFIX) (MEM_ALLOCATION_INFO)? TENSOR_SHAPE TENSOR_DTYPE
  TENSOR_SHAPE: '[' dim0_size, dim1_size, ..., last_dim_size ']'
  MEM_ALLOCATION_INFO: PLANNED_MEM_INFO | UNPLANNED_MEM_INFO
  PLANNED_MEM_INFO: 'm' MEM_LAYER_ID '.' MEM_LAYER_OFFSET
  UNPLANNED_MEM_INFO: 'm.'
```

To make the dump easier to read, it's colored as follows:
1. input/output EValues are marked as red
2. EValue types (or more specifically tensor types with size and dtype) are marked as blue
r   
evalue_idxr#   c                    > S[         [           S[        S[        4S jn[        U 5      nU" TU 5      =nS:  a	  USU S3-  nU" TU 5      =nS:  a	  USU S3-  nT
U    nU[        UT	T5      -   $ )	Niolisttarget_evalue_idxr#   c                 >    [        U 5       H  u  p#X1:X  d  M  Us  $    g)z4
The list is short enough so linear scan is proper.
)	enumerate)r   r   io_idxr   s       rM   _get_io_index9print_program.<locals>._format_arg.<locals>._get_io_index   s&     '0&7"2!M '8 rO   r   z[31mIrj   z[31mO)r   rx   rt   r   )r   r   argstr	input_idx
output_idxrV   inputsrX   outputsrW   valuess         rM   _format_arg"print_program.<locals>._format_arg   s    	$s) 	 	 	 Z&vz::Iq@	)G44F'<<JB	*W55F 
#v|=VWWWrO   z#The program contains the following z instructionsfile3z:  endr   r_   , zJF (z) -> zMOVE z -> zFREE zUnsupport instruction type N)"execution_plan	operators	delegateschainsinstructionsr   r   r   rx   rt   printlenr   rk   
instr_argsr   op_indexargsoverloadnamejoinmapr   delegate_indexidr   cond_value_indexdestination_instructionr   	move_frommove_tor   value_indexr   )r   rW   rX   r   r   r   r   chainr   r   idxinstrkernelopr   opnamer   delegatebackend
backend_idjfcall	move_callr   r   r   s    ``                   @@@rM   print_programr      s   B ++A.N((I((I!!!$E%%L&--F'//G)00FX X X X( 

-c,.?-@NUX  -
Qrl-e&&
33%%F??+B;;D35;;y"++/BGGFXXc+45FVHAfX&S1((,77''H 7 78G==D#JJ<JXXc+45FZL&*5((-88%%F{6#:#:;<E&B`B`Aab (((33((II$7$789k)J[J[>\=]^ (((33E+e&6&6&B&BCDECP"=eW EFFA .rO   objindentc                 ^  ^ ^
 [        T [        R                  R                  5      (       a  [	        [
        R                  S5      e[        T [        5      (       a  [        [        T 5      SUS9  g[        [        [        [        [        S5      4m
[        T T
5      (       a  [        T SUS9  g[        T [        5      (       a7  [        R                   " 5       nSUl        [        UR%                  T 5      SUS9  g[        T [&        5      (       a  [)        T 5      S:  a#  [+        S T  5       5      (       a  [        T SUS9  g[        SUS	9  [-        T 5       H1  u  pE[        S
US-   -  SUS9  [/        XQS-   US9  [        SU S3US	9  M3     [        S
U-  S-   SUS9  g[+        U U
4S j[1        T 5       5       5      nU(       a  SOSn[        [        T 5      R2                   S3XrS9  [-        [1        T 5      5       H  u  pU(       d  [        S
US-   -  SUS9  [        U	R4                  S-   SUS9  [/        [7        T U	R4                  5      US-   US9  U[)        [1        T 5      5      S-
  :  a  [        SSUS9  [        SXrS9  M     U(       d  [        S
U-  SUS9  [        SU(       a  SOSUS9  g)ua   
Pretty prints the given object which is of the Program type and any of its
attribute’s types.
z4pretty_print() does not accept GraphModule as input.r   r   Ni   
   c              3   B   #    U  H  n[        U[        5      v   M     g 7frR   )rk   rx   ).0elems     rM   	<genexpr>pretty_print.<locals>.<genexpr>  s      G34D#!6!63s   [r   z     )r   z(index=z),]c              3   d   >#    U  H%  n[        [        TUR                  5      T5      v   M'     g 7frR   )rk   getattrr   )r   fieldr   
primitivess     rM   r   r     s)      FQU
73

+Z88ks   -0
(=z, ))rk   torchfxGraphModuler	   r
   INVALID_INPUT_TYPEr   r   rx   rt   boolfloattypebytesreprlibReprmaxotherreprlistr   allr   pretty_printr   __name__r   r   )r   r   r   rindexr   inliner   r(   _fieldr   s   `         @rM   r   r      sN   
 #uxx++,,..B
 	
 #wc#hBS)sD%d4J#z""cr$#uLLN
affSkr,#ts8b=S G3 GGG#2C(c$S>KE$&1*%2C8zs3GE7"%C0 * 	dVmc!r4 FLSk F "DC	T#Y 
"6vc{+	$&1*%2C8fkkCRc2WS&++.
Ds6#;!##$BS)bc$ , dVm#.	#2T4rO   c                     SnU R                    HP  nUSUR                   S3-  nUS[        UR                  5       SUR                   S3-  nXR
                   S3-  nMR     US-  nU$ )z1
Pretty prints the traceback for one instruction
z$Traceback (most recent call last): 
z
    File "z", zline z, in r   z 
)ru   filenamert   linenor   context)r   prettyframes      rM   pretty_print_stacktracesr   0  sy     5FJu~~.c22E#ell+,E%**R@@]]O3''  dNFMrO   graphfinding_nodec                     [         R                  " U 5      nSn[        U R                  5       H  u  pEXQ:X  d  M  UnM     S[        R
                  R                  S[        S[        4S jnU" X#5      $ )a  
Insert a cursor at the node location in the fx.Graph.
e.g:
# graph():
#   %x : [#users=1] = placeholder[target=x]
#   %param : [#users=1] = get_attr[target=param]
#   %add : [#users=1] = call_function[target=operator.add](args = (%x, %param), kwargs = {})
# --> %linear : [#users=1] = call_module[target=linear](args = (%add,), kwargs = {})
#   %clamp : [#users=1] = call_method[target=clamp](args = (%linear,), kwargs = {min: 0.0, max: 1.0})
#   return clamp

This is mostly used for error reporting
r   r   offending_node_idxr#   c                     Sn[        U R                  5       H5  u  p4UR                  5       nU(       d  M  X1:w  a
  USU-   -  nM-  USU-   -  nM7     U$ )Nzgraph():z
    z
--> )r   nodesformat_node)r   r   r'   ixnodenode_strs         rM   _format_graph*add_cursor_to_graph.<locals>._format_graphT  sZ    !%++.HB'')Hx+H,,AH,,A / rO   )	copydeepcopyr   r   r   r   Graphrx   rt   )r   r   	new_graphfound_atr   r   r   s          rM   add_cursor_to_graphr  =  sf     e$IHekk*H +
	UXX^^ 	 	 	 --rO   
stacktracec                    Sn[         R                  " X5      n[        U5       VVs/ s HI  u  p4[        US   [	        US   5      US   U R                  S5      US-  S-      R                  5       S9PMK     nnn[        U5      $ s  snnf )z.Creates a frame list from a stacktrace string.z$File "(.*?)", line (\d+), in (.*?)\nr   r      r   )r   r   r   r   )refindallr   r   rx   splitstripr   )r  patternmatchesr(   matchmapped_frame_lists         rM   _stacktrace_to_framelistr  b  s    5Gjj-G "'* +HA 	1XuQx=q$$T*1q5195;;=		
 +   &''s   ABr   c                    [        X5      nSU SU S3n[        UR                  S5      (       a  USUR                  S    S3-  nSUR                  ;   a*  [        UR                  S   5      nUS[	        U5       S3-  nU$ )	a\	  
Inspect a node by highlighting the node in the graph as well as the stacktrace.

Args:
    graph: The graph containing the node
    node: The node to be inspected

Return: A string. An example output is:

_param_constant0 error_msg:  Here is the failing node in the graph module:
graph():
    %arg0_1 : [num_users=1] = placeholder[target=arg0_1]
--> %_param_constant0 : [num_users=1] = get_attr[target=_param_constant0]
    %_param_constant1 : [num_users=1] = get_attr[target=_param_constant1]
    %aten_convolution_default : [num_users=2] = call_function[target=executorch.exir.dialects.edge._ops.aten.convolution.default](args = (%arg0_1, %_param_constant0, %_param_constant1, [1, 1], [0, 0], [1, 1], False, [0, 0], 1), kwargs = {})
    %_param_constant2 : [num_users=1] = get_attr[target=_param_constant2]
    %_param_constant3 : [num_users=1] = get_attr[target=_param_constant3]
    %aten_convolution_default_1 : [num_users=1] = call_function[target=executorch.exir.dialects.edge._ops.aten.convolution.default](args = (%aten_convolution_default, %_param_constant2, %_param_constant3, [1, 1], [0, 0], [1, 1], False, [0, 0], 1), kwargs = {})
    %aten_add_tensor : [num_users=1] = call_function[target=executorch.exir.dialects.edge._ops.aten.add.Tensor](args = (%aten_convolution_default, %aten_convolution_default_1), kwargs = {})
    %_param_constant4 : [num_users=1] = get_attr[target=_param_constant4]
    %_param_constant5 : [num_users=1] = get_attr[target=_param_constant5]
    %aten_convolution_default_2 : [num_users=1] = call_function[target=executorch.exir.dialects.edge._ops.aten.convolution.default](args = (%aten_add_tensor, %_param_constant4, %_param_constant5, [1, 1], [0, 0], [1, 1], False, [0, 0], 1), kwargs = {})
    %aten_gelu_default : [num_users=1] = call_function[target=executorch.exir.dialects.edge._ops.aten.gelu.default](args = (%aten_convolution_default_2,), kwargs = {})
    return [aten_gelu_default]
This node _param_constant0 has metadata of:
The node stacktrace:
Traceback (most recent call last):
    File "/tmp/ipykernel_1204253/3382880687.py", line 7, in forward
return self.test_model(x)
    File "/mnt/xarfuse/uid-25337/7b86ad0c-seed-nspid4026532987_cgpid2707357-ns-4026532984/torch/nn/modules/module.py", line 1528, in _call_impl
return forward_call(*args, **kwargs)
    File "/tmp/ipykernel_1204253/712280972.py", line 10, in forward
a = self.conv1(x)

z&Here is the node in the graph module:
z
This node z has metadata of:
speczThe node spec:
r   stack_tracezThe node stacktrace:
)r  hasattrmetar  r   )r   r   graph_str_with_cursor	error_msg	framelists        rM   inspect_noder  r  s    H 0<
1 
! "F-	/  tyy&!!'		&(9':"==	 		!,TYY}-EF	-.Fy.Q-RRTUU	rO   )TFN)r   N)7r   r  r   dataclassesr   enumr   typingr   r   r   r   r   executorch.exir.errorr	   r
   r   executorch.exir.schemar   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   rt   rN   r   rU   r   r   rx   r   r   r   r  Noder  r  r   rO   rM   <module>r!     s    	    . .  M M     4*  6?V ? ?CC"&CCGCCP &+ 	aGaGaG  $aG 
&		aG
 
aGJ65c 653 65&1A 65T 65r
) 
 
".uxx~~ ".UXX]] ".s ".J( ( ( 2 2ehhmm 2 2rO   