
    i2A                         S SK r S SKrS SKrS SKrS SKrS SKrS SKJr  S SKJ	r	J
r
  S SKJs  Js  Js  Jr  S SKrS SKrS SKJr  S SKJr  S SKJr   " S S5      r " S	 S
5      rS\S\S\	\
\R:                        4S jrg)    N)Path)SequenceTuple)QcomChipset)dump_context_from_pte)Digraphc                   j    \ rS rSr SS\S\S\R                  /4S jjrS rS r	S r
S	 rS
 rS rSrg)	DrawGraph   filename	directorypy_op_wrapper_listc                     Xl         X l        X0l        [        USS9U l        U R                  R                  SS9  X@l        U R                  5         g )Nsvg)formatTB)rankdir)r   r   r   r   dotattr
dot_stringdraw)selfr   r   r   r   s        j/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/backends/qualcomm/debugger/utils.py__init__DrawGraph.__init__   sB     !""48E2d#$		    c                     X;   a  g UR                  U5        X1   S   nU H0  nU R                  R                  XQ5        U R                  XRU5        M2     g )N
input_list)addr   edgedfs_add_edges)r   	node_namevisited	node_listr   input_node_names         r   r!   DrawGraph.dfs_add_edges#   sN    I),7
)OHHMM/5C  *r   c                     [        5       n0 n/ nU R                  U5        U R                  X#5        U R                  U5        UR	                  5        H  u  pEXA;  d  M  U R                  XAU5        M      U R                  $ )N)setget_nodeadd_nodeto_excelitemsr!   r   )r   r#   r$   
excel_datar"   _s         r   get_dot_graphDrawGraph.get_dot_graph-   sm    %	
i i,j! &OO-LI'""9yA . xxr   c                    U R                    GHE  nUR                  5       n[        UR                  5       S   5       GH  nUR                  5       S   S   R                  S:X  a  UR                  5       S   U   R
                  nUR                  n/ n[        UR                  5       S   5       H{  nUR                  5       S   U   R                  S:X  aK  UR                  5       S   U   R
                  n	U	R                  n
X;  a  U	/ S.X'   UR                  U
5        Mr  [        S5      e   Xa;  a  XWS.X'   M  XqU   S	'   GM  [        S5      e   GMH     g )
NnumOfOutputsoutputTensorsr      numOfInputsinputTensors)noder   zUnsupported tensor versionr   )	r   GetOpWrapperrangeGetOpConfigversionv2nameappend
ValueError)r   r$   py_op_wrapper
op_wrapperir7   r"   r   j
input_noder%   s              r   r)   DrawGraph.get_node=   sQ   !44M&335J:113NCD))+O<Q?GG1L%113ODQGJJD $		I!#J":#9#9#;M#JK%113NCAFNNRSS)3)?)?)A.)QRS)T)W)WJ.8ooO.?,624>"	 : '--o>",-I"JJ L !18</W	,=G),\:$%ABB- E 5r   c                 0   UR                  5        GH  u  p4US   nUnUR                  nUR                  nUR                  n	UR                  R
                  n
/ n/ nU
[        R                  R                  :X  a_  UR                  UR                  R                  R                  5        UR                  UR                  R                  R                  5        OU
[        R                  R                  :X  a  [        UR                  R                  R                   5       H{  nUR                  UR                  R                  R"                  U   R                  5        UR                  UR                  R                  R"                  U   R                  5        M}     UR                  UUUUS.5        SnSU;   d  SU;   a  SnOUS:X  a  SnS	U S
U SU SU SU SU SU SU	 SU SU
 S3nUS-  nU R$                  R'                  UUSSSSS9  GM     g )Nr7   )r=   tensor_typescaleoffsetwhiteinputoutput
lightgreen   	lightpinkzu<
                <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4">
                <TR><TD BGCOLOR="z">name: z,</TD></TR>
                <TR><TD BGCOLOR="z">data_type: z">tensor_type: z">dims: z">quantization_encoding: z</TD></TR>
            z	</TABLE>>boxroundedtransparentblack)shapestyle	fillcolorcolor)r,   dataTypetype
dimensionsquantizeParamsquantizationEncodingPyQnnManagerQnn_QuantizationEncoding_t&QNN_QUANTIZATION_ENCODING_SCALE_OFFSETr>   scaleOffsetEncodingrH   rI   +QNN_QUANTIZATION_ENCODING_AXIS_SCALE_OFFSETr9   axisScaleOffsetEncodingnumScaleOffsetsscaleOffsetr   r7   )r   r$   r-   r"   tensorr7   r=   	data_typerG   dimsquantization_encodingrH   rI   rB   bg_colorlabels                   r   r*   DrawGraph.add_nodeY   s-   !*!2I&>DDI))K??D$($7$7$L$L!EF%::aab T00DDJJKd11EELLM%::ffg ''??OOA LL++CCOOPQRXX MM++CCOO &  #."$	 H)#x9'<'!&""*8D6 :""*= D""*?;- H""*8D6 :""*+DEZD[ \E [ EHHMM'  k "3r   c                    / n/ nU H]  nUS   nUS   nUS   nUS   [         R                  R                  :X  a  UR                  XVUS.5        MI  UR                  XVUS.5        M_     [        R
                  " U5      n[        R
                  " U5      n	U R                   S3n
[        R                  " U
5       nUR                  USSS	9  U	R                  US
SS	9  S S S 5        g ! , (       d  f       g = f)Nr=   rH   rI   rG   )r=   rH   rI   z.xlsx
ParametersF)
sheet_nameindexScales)	r]   Qnn_TensorType_tQNN_TENSOR_TYPE_STATICr>   pd	DataFramer   ExcelWriterr+   )r   r-   
param_rowsactivation_rowsentryr=   rH   rI   param_dfscale_dfoutput_filewriters               r   r+   DrawGraph.to_excel   s    
E=D'NE8_Fm$00GGH !!46"RS&&PV'WX   <<
+<<0u-^^K(FfUKfG )((s   9#C%%
C3c                    U R                  5       n[        R                  " 5        nU S3nUR                  U R                  USU R
                  (       + S9  [        R                  R                  X0R                   S35      n[        R                  R                  U R                  U R                   S35      n[        R                  " XE5        U R
                  (       aw  [        R                  R                  X0R                   5      n[        R                  R                  U R                  U R                   S35      n[        R                  " Xg5        S S S 5        g ! , (       d  f       g = f)Nz/outputsr   )r   r   cleanupz.svgz.dot)r/   tempfileTemporaryDirectoryrenderr   r   ospathjoinr   shutilmove)r   graphtmp_dirtemp_directorysource_filedestination_filedot_filedot_dest_files           r   r   DrawGraph.draw   s    ""$((*g 'y1NLL( OO+	   '',,~--7MNK!ww||DNNt}}oT<RSKK677<<==/K "T^^d=S TH4 +**s   D2E!!
E/)r   r   r   r   r   N)F)__name__
__module____qualname____firstlineno__strr]   PyQnnOpWrapperr   r!   r/   r)   r*   r+   r   __static_attributes__ r   r   r
   r
      sS       *889	D C8=~H.5r   r
   c                   N    \ rS rSr S	S jr  S
S jrSS jrSS jr SS jrSr	g)QnnTool   c                    [         R                  R                  SS 5      U l        [         R                  R                  SS 5      U l        U R                  (       d   S5       eU R                  (       d   S5       eXl        X`l        X@l        X l        XPl	        [        [        [        5      R                  5       R                  S   5      U l        SSS00S	S
SSS./[!        U5      S./0S.U l        g )NQNN_SDK_ROOTANDROID_NDK_ROOTz2QNN_SDK_ROOT was not found in environment variablez6ANDROID_NDK_ROOT was not found in environment variable   backend_extensionsconfig_file_pathzconfig.jsondeviceslintingburstd   )perf_profilerpc_control_latency)profiling_levelcoressoc_id)backend_extension_configconfig)r   environgetqnn_sdkndkr   	workspaceadbsample_inputbuild_folderr   r   __file__resolveparentsrootintr   )r   r   r   r   r   r   r   s          r   r   QnnTool.__init__   s     zz~~nd;::>>"4d;||QQQ|xxQQQx"((X..088;<	 %&') +4-4SQ" #&f+

r   c                    U R                   R                  5        H?  u  p4[        U R                   SU S3S5       n[        R
                  " XESS9  S S S 5        MA     SnU R                   SU S3S	U R                   S
U S3SU R                   S
U S3SU R                   SU 3SU R                   S3SU 3SU R                   3SS/n[        R                  " SR                  U5      SSSS9n[        R                  R                  U R                   SU S35      (       d   UR                  5       eg ! , (       d  f       GM,  = f)N/.jsonwrN   indentx86_64-linux-clang/bin/z/qnn-context-binary-generatorz	--backend/lib/z/libQnnHtp.soz--modelz/libQnnModelDlc.soz
--dlc_pathz--config_file /backend_extension_config.jsonz--binary_file z--output_dir --profiling_level detailed--profiling_option optrace T	/bin/bashshell
executablecapture_output.bin)r   r,   openr   jsondumpr   
subprocessrunr   r   r   isfilestderr)	r   qnn_binary_filebinary_name	file_namedata	json_filetargetcmdsresults	            r   qnn_context_binary_generator$QnnTool.qnn_context_binary_generator   sI   
  ${{002OIa	{%8#>)		$!4 ?>  3 &||nE&)FG||nE&7||nE&);<||nAo./T\\N*HI[M*DLL>*((
 HHTN"	
 ww~~a}DABBQFMMQB1 ?>s   D77
E	c                    SU R                   S   S   S'   U R                   R                  5        H?  u  p#[        U R                   SU S3S5       n[        R
                  " X4SS	9  S S S 5        MA     S
nU R                   SU S3U R                   S3U R                   S3U R                   SU S3U R                   SU S3/nSU R                   S3SU R                   S3SU R                   S3SSSSU S3SSSSS/nU R                  R                  U R                  US9  U R                  R                  S R                  U5      S!9  U R                  R                  S"S#U R                   S$3U R                  /5        [        R                  R!                  U R                   S%35      (       d   S&U R                   35       eg ! , (       d  f       GM  = f)'Nz./libQnnHtpNetRunExtensions.sor   r   shared_library_pathr   r   r   rN   r   zaarch64-androidr   z/libQnnHtpNetRunExtensions.sor   z/config.jsonr   r   z/qnn-net-runzexport LD_LIBRARY_PATH=z &&zexport ADSP_LIBRARY_PATH=zcd z./qnn-net-runz--backend libQnnHtp.soz--input_list input_list.txtz--retrieve_context z--use_native_input_filesz--use_native_output_filesz+--config_file backend_extension_config.jsonr   r   )inputsfilesr   )custom_runner_cmdpullz-az /output/qnn-profiling-data_0.log/qnn-profiling-data_0.logz-Error: qnn-profiling-data_0.log not found in )r   r,   r   r   r   r   r   r   r   pushr   executer   _adbr   r   r   )r   
graph_namer   r   r   r   r   r   s           r   qnn_net_runQnnTool.qnn_net_run
  s    - 	./0DE!	
  ${{002OIa	{%8#>)		$!4 ?>  3 #||nE&)FG||n:;||nL)||nAj\.||nE&6
 &dnn%5S9''7s;$..!%$)!*T2&'9((
 	$$ 	 	
 	388D>:>>""BC		
 ww~~||n56
 
 	J:4<<.I	J 
O ?>s   G


G	c           
         SSS00U R                   S'   U R                   R                  5        H?  u  p4[        U R                   SU S3S5       n[        R
                  " XESS	9  S S S 5        MA     S
nU R                   SU S3SU R                   S3SU R                   SU S3SU R                   SU S3SU R                   S3SU R                   SU S3/n[        R                  " SR                  U5      SSSS9nUR                  S:X  d#   SUR                  R                  S5       35       eg ! , (       d  f       GM  = f)Nfeatures	qhas_jsonTr   r   r   r   rN   r   r   r   z/qnn-profile-viewerz	--config r   z--schematic r   z	--reader r   z#/libQnnHtpOptraceProfilingReader.soz--input_log r   z	--output z	/optrace_r   r   r   r   zProcess failed with error: zutf-8)r   r,   r   r   r   r   r   r   r   r   r   
returncoder   decode)	r   r   	graph_idxr   r   r   r   r   r   s	            r   qnn_profile_viewerQnnTool.qnn_profile_viewer;  sU   3=T?R2S./#{{002OIa	{%8#>)		$!4 ?>  3 &||nE&)<=~%CD499+Qzl$7~U6(2UV4<<.(AB~Yyk?
 HHTN"	
 "	I()=)=g)F(GH	I"' ?>s   D44
E	c                 .   [         R                  R                  U5      u  p#US;   d   SU S35       e[        R                  " SU5      nUnSnU(       a+  UR                  S5      n[        UR                  S5      5      nUS:X  a  U R                  X S	35        U S	3nU R                  US
9  U R                  U S3US9  [         R                  R                  U R                  U S35      n[         R                  R                  U5      (       a  [         R                  " U5        [         R                  R                  U R                  SU S35      n[         R                  R                  U R                  SU S35      n	[         R                  R                  U5      (       a$  [         R                  R                  U	5      (       dH   S[         R                  R                  U5       S[         R                  R                  U	5       S35       eX4$ )a  
Generate Qnn HTP Optrace Profiling https://docs.qualcomm.com/bundle/publicresource/topics/80-63442-10/htp_backend.html#qnn-htp-optrace-profiling
and QNN HTP Analysis Summary (QHAS) https://docs.qualcomm.com/bundle/publicresource/topics/80-63442-10/htp_backend.html#qnn-htp-analysis-summary-qhas
. You can utilize the QAIRT Visualizer (https://pypi.org/project/qairt-visualizer/) to visualize the results from the files above.
).dlcr   zInvalid file extension 'z,'. Supported extensions are 'dlc' and 'bin'.z^(.*)_(\d+)$r      r4   r   z.serialized)r   
_schematic)r   r   z_schematic.binoptrace_r   z_qnn_htp_analysis_summary.jsonz)Error: Required files not found - either z or z is missing.)r   r   splitextrematchgroupr   r   r   r   r   r   r   remover   basename)
r   r   r   file_extensionr   graph_base_namer   schematic_bin_pathoptrace_path	qhas_paths
             r   generate_optraceQnnTool.generate_optraceT  s    &(WW%5%5o%F"
 "
 
 	c &n%55ab	c 
 *5$	#kk!nOEKKN+I V#--#4K!@ ,,K8J 	J/)**5 	  	

  WW\\$))7H5WX77>>,--II()ww||DLLHYKu2MNGGLLLLHYK/MN
	 ww~~l++y0I0I 	
7ww-.d2773C3CI3N2O|]	
I
 &&r   )	r   r   r   r   r   r   r   r   r   N)z#/data/local/tmp/qnn_executorch_test)forward_0.dlcforward.serialized)r  )forward_schematicr   )r  )
r   r   r   r   r   r   r   r   r  r   r   r   r   r   r      s3     8%
R ((R@/JbI6 (3'r   r   r   pte_pathr   c           	      l   [         R                  R                  UR                  [         R                  5      S   5      u  pV[        U5      n[        U UUUUR                  UR                  S9n0 n	U H=  n
U
R                  [         R                  5      S   nUR                  U5      u  pX4X'   M?     U	$ )a  
Generate optrace and QHAS (QNN HTP Analysis Summary) JSON files.

Args:
    artifact (str): Path to the artifact folder.
    adb (SimpleADB): An object for communicating with Android device
    pte_path (str): The path to the generated PTE file, including the file extension (e.g., model.pte).
    inputs Sequence((Tuple[torch.Tensor])): The input tensors for the model.


Returns:
    dict: A dictionary where keys are the dumped file paths and values are tuples containing the paths
    to the generated optrace and QHAS JSON files.
)r   r   )
r   r   r   splitsepr   r   
build_pathr   r  )artifactr   r   r  r   r   r.   	dumpfilesqnn_toolbinaries_tracefileoptraceqhass                r   r  r    s    * ''""8>>"&&#9"#=>KH &h/I ^^--H N::bff%b) 11(; '  r   )r   r   r   r   r   r   pathlibr   typingr   r   7executorch.backends.qualcomm.python.PyQnnManagerAdaptorbackendsqualcommpythonPyQnnManagerAdaptorr]   pandasrs   torch4executorch.backends.qualcomm.serialization.qc_schemar   (executorch.backends.qualcomm.utils.utilsr   graphvizr   r
   r   r   Tensorr  r   r   r   <module>r"     s{     	 	     " N N   L J l5 l5^E' E'P)) 	)
 U5<<())r   