Skip to content

Commit 9c27273

Browse files
Qualcomm AI Engine Direct - QAIRT Visualizer Engagement
Summary: - Add QAIRT Visualizer e2e example script. - Add README for QAIRT Visualizer. - Integrate QAIRT Visualizer into CI. - Remove redundant context size log in QnnDlcManager to avoid duplicate log message. - Remove DLC test case from context extraction, as it has already been covered in the generate optrace test case.
1 parent 05383fe commit 9c27273

File tree

10 files changed

+611
-212
lines changed

10 files changed

+611
-212
lines changed

backends/qualcomm/debugger/README.md

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# QAIRT Visualizer
2+
3+
[QAIRT Visualizer](https://pypi.org/project/qairt-visualizer/) is a Python package designed to help you visualize and analyze data from Qualcomm AI Engine Direct (QNN) models. It provides tools to generate and interpret op traces (`optrace`) and QNN HTP Analysis Summary (`QHAS`), enabling detailed insights into your model's performance and behavior.
4+
5+
## Installation
6+
7+
You can install the QAIRT Visualizer package directly from [QAIRT Visualizer](https://pypi.org/project/qairt-visualizer/):
8+
9+
```bash
10+
pip install qairt-visualizer
11+
```
12+
13+
## Quick start
14+
This command launches an interactive GUI interface to visualize the `optrace` and `QHAS` results.
15+
```
16+
python -m examples.qualcomm.util_scripts.qairt_visualizer_demo -H ${host} -s {device} -b build-android -a ${path_to_output_folder} --online_prepare
17+
```
18+
- If online prepare mode is `enabled`, the following artifacts will be generated:
19+
- `model`.dlc
20+
- `optrace`.json
21+
- `QHAS`
22+
- If online prepare mode is `disabled`, the following artifacts will be generated:
23+
- `model`.bin
24+
- `optrace`.json
25+
- `QHAS`.json
26+
27+
Note: Model visualization is supported only in online prepare mode.
28+
The `.bin` format is not compatible with the QAIRT visualizer.
29+
To enable model visualization, please add the `--online_prepare` flag.
30+
31+
## Details
32+
### 1. Lower to QNN backend
33+
Generate an ExecuTorch binary for Qualcomm platforms.
34+
```python
35+
build_executorch_binary(
36+
model,
37+
example_input,
38+
args.model,
39+
f"{args.artifact}/{pte_filename}",
40+
[example_input],
41+
quant_dtype=QuantDtype.use_8a8w,
42+
online_prepare=args.online_prepare,
43+
optrace=True,
44+
)
45+
```
46+
### 2. Generate optrace and QHAS
47+
Generate optrace and QHAS files using QNN tools under $QNN_SDK_ROOT. After finishing, you will get a `binaries_trace` dictionary.
48+
``` python
49+
adb = SimpleADB(
50+
qnn_sdk=os.getenv("QNN_SDK_ROOT"),
51+
build_path=f"{args.build_folder}",
52+
pte_path=f"{args.artifact}/{pte_filename}.pte",
53+
workspace=f"/data/local/tmp/executorch/{pte_filename}",
54+
device_id=args.device,
55+
host_id=args.host,
56+
soc_model=args.model,
57+
)
58+
binaries_trace = generate_optrace(
59+
args, adb, f"{args.artifact}/{pte_filename}.pte", example_input
60+
)
61+
```
62+
- **`binaries_trace`**: A dictionary where keys are the dumped file paths and values are tuples containing the paths to the generated optrace and QHAS JSON files.
63+
64+
- Example 1: {"forward_0.dlc": (optrace.json, optrace_qnn_htp_analysis_summary.json)}
65+
- Example 2: {"forward_0.bin": (optrace.json, optrace_qnn_htp_analysis_summary.json)}
66+
67+
### 3. Visualizing and Analyzing optrace and QHAS
68+
69+
Once you have the optrace and QHAS files, you can leverage the QAIRT Visualizer to visualize the model graph, optrace and QHAS data. Here's how you can do it:
70+
71+
```python
72+
import qairt_visualizer
73+
qairt_visualizer.view(f"{args.artifact}/forward_0.dlc", reports=[optrace, qhas])
74+
```
75+
or
76+
```python
77+
import qairt_visualizer
78+
qairt_visualizer.view(reports=[optrace, qhas])
79+
```
80+
81+
- `model`: Path to your QNN model file (e.g., `path_to_your_model.dlc`).
82+
- **`reports`**: List of report file paths, including the optrace (`optrace.json`) and QHAS (`optrace_qnn_htp_analysis_summary.json`).
83+
84+
Note: Files ending with `.bin ` do not support graph visualization in qairt_visualizer.
85+
86+
## Demo
87+
88+
<figure>
89+
<img src="assets/qairt_visualizer_demo.png" alt="QAIRT visualizer demo"> <figcaption>
90+
</figcaption>
91+
</figure>
92+
93+
For more details, visit the [QAIRT Visualizer](https://pypi.org/project/qairt-visualizer/).
Loading

backends/qualcomm/debugger/utils.py

Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
1+
import json
12
import os
3+
import re
24
import shutil
5+
import subprocess
36
import tempfile
7+
from pathlib import Path
8+
from typing import Tuple
49

510
import executorch.backends.qualcomm.python.PyQnnWrapperAdaptor as PyQnnWrapper
611
import pandas as pd
12+
import torch
13+
from executorch.backends.qualcomm.serialization.qc_schema import QcomChipset
14+
from executorch.backends.qualcomm.utils.utils import dump_context_from_pte
15+
716
from graphviz import Digraph
817

918

@@ -180,3 +189,255 @@ def draw(self):
180189
dot_file = os.path.join(temp_directory, f"{self.filename}")
181190
dot_dest_file = os.path.join(".", f"{self.filename}.dot")
182191
shutil.move(dot_file, dot_dest_file)
192+
193+
194+
class QnnTool:
195+
def __init__(
196+
self,
197+
tmp_dir,
198+
sample_input,
199+
soc_id,
200+
adb,
201+
build_folder,
202+
workspace="/data/local/tmp/qnn_executorch_test",
203+
):
204+
self.qnn_sdk = os.environ.get("QNN_SDK_ROOT", None)
205+
self.ndk = os.environ.get("ANDROID_NDK_ROOT", None)
206+
assert self.qnn_sdk, "QNN_SDK_ROOT was not found in environment variable"
207+
assert self.ndk, "ANDROID_NDK_ROOT was not found in environment variable"
208+
209+
self.tmp_dir = tmp_dir
210+
self.workspace = workspace
211+
self.adb = adb
212+
self.sample_input = sample_input
213+
self.build_folder = build_folder
214+
self.root = str(Path(__file__).resolve().parents[3])
215+
self.config = {
216+
"backend_extension_config": {
217+
"backend_extensions": {
218+
"config_file_path": "config.json",
219+
},
220+
"features": {
221+
"qhas_json": True,
222+
},
223+
},
224+
"config": {
225+
"devices": [
226+
{
227+
"profiling_level": "linting",
228+
"cores": [
229+
{"perf_profile": "burst", "rpc_control_latency": 100}
230+
],
231+
"soc_id": int(soc_id),
232+
}
233+
]
234+
},
235+
}
236+
237+
def qnn_context_binary_generator(
238+
self,
239+
qnn_binary_file="forward_0.dlc",
240+
binary_name="forward.serialized",
241+
):
242+
for file_name, data in self.config.items():
243+
with open(f"{self.tmp_dir}/{file_name}.json", "w") as json_file:
244+
json.dump(data, json_file, indent=4)
245+
246+
target = "x86_64-linux-clang"
247+
cmds = [
248+
f"{self.qnn_sdk}/bin/{target}/qnn-context-binary-generator",
249+
"--backend",
250+
f"{self.qnn_sdk}/lib/{target}/libQnnHtp.so",
251+
"--model",
252+
f"{self.qnn_sdk}/lib/{target}/libQnnModelDlc.so",
253+
"--dlc_path",
254+
f"{self.tmp_dir}/{qnn_binary_file}",
255+
f"--config_file {self.tmp_dir}/backend_extension_config.json",
256+
f"--binary_file {binary_name}",
257+
f"--output_dir {self.tmp_dir}",
258+
"--profiling_level detailed",
259+
"--profiling_option optrace",
260+
]
261+
result = subprocess.run(
262+
" ".join(cmds),
263+
shell=True,
264+
executable="/bin/bash",
265+
capture_output=True,
266+
)
267+
assert os.path.isfile(f"{self.tmp_dir}/{binary_name}.bin"), result.stderr
268+
269+
def qnn_net_run(self, graph_name="forward.serialized"):
270+
input_list = ""
271+
for idx, _ in enumerate(self.sample_input):
272+
input_name = f"input_{idx}_0.raw"
273+
input_list += input_name + " "
274+
input_list = input_list.strip() + "\n"
275+
276+
self.config["backend_extension_config"]["backend_extensions"][
277+
"shared_library_path"
278+
] = "./libQnnHtpNetRunExtensions.so"
279+
for file_name, data in self.config.items():
280+
with open(f"{self.tmp_dir}/{file_name}.json", "w") as json_file:
281+
json.dump(data, json_file, indent=4)
282+
283+
target = "aarch64-android"
284+
files = [
285+
f"{self.qnn_sdk}/lib/{target}/libQnnHtpNetRunExtensions.so",
286+
f"{self.tmp_dir}/backend_extension_config.json",
287+
f"{self.tmp_dir}/config.json",
288+
f"{self.tmp_dir}/{graph_name}.bin",
289+
f"{self.qnn_sdk}/bin/{target}/qnn-net-run",
290+
]
291+
cmds = [
292+
f"export LD_LIBRARY_PATH={self.workspace} &&",
293+
f"export ADSP_LIBRARY_PATH={self.workspace} &&",
294+
f"cd {self.workspace} &&",
295+
"./qnn-net-run",
296+
"--backend libQnnHtp.so",
297+
"--input_list input_list.txt",
298+
f"--retrieve_context {graph_name}.bin",
299+
"--use_native_input_files",
300+
"--use_native_output_files",
301+
"--config_file backend_extension_config.json",
302+
"--profiling_level detailed",
303+
"--profiling_option optrace",
304+
]
305+
self.adb.push(
306+
inputs=self.sample_input,
307+
input_list=input_list,
308+
files=files,
309+
)
310+
self.adb.execute(custom_runner_cmd=" ".join(cmds))
311+
self.adb._adb(
312+
[
313+
"pull",
314+
"-a",
315+
f"{self.workspace}/output/qnn-profiling-data_0.log",
316+
self.tmp_dir,
317+
]
318+
)
319+
320+
assert os.path.isfile(
321+
f"{self.tmp_dir}/qnn-profiling-data_0.log"
322+
), f"Error: qnn-profiling-data_0.log not found in {self.tmp_dir}"
323+
324+
def qnn_profile_viewer(self, graph_name="forward_schematic", graph_idx=0):
325+
self.config["backend_extension_config"]["backend_extensions"][
326+
"shared_library_path"
327+
] = "./libQnnHtpNetRunExtensions.so"
328+
self.config["backend_extension_config"] = {"features": {"qhas_json": True}}
329+
for file_name, data in self.config.items():
330+
with open(f"{self.tmp_dir}/{file_name}.json", "w") as json_file:
331+
json.dump(data, json_file, indent=4)
332+
333+
target = "x86_64-linux-clang"
334+
cmds = [
335+
f"{self.qnn_sdk}/bin/{target}/qnn-profile-viewer",
336+
f"--config {self.tmp_dir}/backend_extension_config.json",
337+
f"--schematic {self.root}/{graph_name}.bin",
338+
f"--reader {self.qnn_sdk}/lib/{target}/libQnnHtpOptraceProfilingReader.so",
339+
f"--input_log {self.tmp_dir}/qnn-profiling-data_0.log",
340+
f"--output {self.tmp_dir}/optrace_{graph_idx}.json",
341+
]
342+
result = subprocess.run(
343+
" ".join(cmds),
344+
shell=True,
345+
executable="/bin/bash",
346+
capture_output=True,
347+
)
348+
assert (
349+
result.returncode == 0
350+
), f"Process failed with error: {result.stderr.decode('utf-8')}"
351+
352+
def generate_optrace(
353+
self,
354+
qnn_binary_file="forward_0.dlc",
355+
):
356+
"""
357+
Generate Qnn HTP Optrace Profiling https://docs.qualcomm.com/bundle/publicresource/topics/80-63442-50/htp_backend.html#qnn-htp-optrace-profiling
358+
and QNN HTP Analysis Summary (QHAS) https://docs.qualcomm.com/bundle/publicresource/topics/80-63442-50/htp_backend.html#qnn-htp-analysis-summary-qhas
359+
. You can utilize the QAIRT Visualizer (https://pypi.org/project/qairt-visualizer/) to visualize the results from the files above.
360+
"""
361+
graph_name, file_extension = os.path.splitext(qnn_binary_file)
362+
assert file_extension in [
363+
".dlc",
364+
".bin",
365+
], f"Invalid file extension '{file_extension}'. Supported extensions are 'dlc' and 'bin'."
366+
367+
# Attempt to extract a numeric index from the end of the graph name (e.g., "forward_123")
368+
match = re.match(r"^(.*)_(\d+)$", graph_name)
369+
graph_base_name = graph_name
370+
graph_idx = 0
371+
372+
if match:
373+
graph_base_name = match.group(1)
374+
graph_idx = int(match.group(2))
375+
376+
# Handle .dlc file extension by generating a serialized version of the graph
377+
if file_extension == ".dlc":
378+
self.qnn_context_binary_generator(
379+
qnn_binary_file, f"{graph_base_name}.serialized"
380+
)
381+
graph_name = f"{graph_base_name}.serialized"
382+
383+
# Run the QNN graph and generate the schematic
384+
self.qnn_net_run(graph_name=graph_name)
385+
self.qnn_profile_viewer(
386+
graph_name=f"{graph_base_name}_schematic", graph_idx=graph_idx
387+
)
388+
389+
# Clean up the schematic binary file if it exists
390+
schematic_bin_path = os.path.join(self.root, f"{graph_base_name}_schematic.bin")
391+
if os.path.isfile(schematic_bin_path):
392+
os.remove(schematic_bin_path)
393+
394+
optrace_path = os.path.join(self.tmp_dir, f"optrace_{graph_idx}.json")
395+
qhas_path = os.path.join(
396+
self.tmp_dir, f"optrace_{graph_idx}_qnn_htp_analysis_summary.json"
397+
)
398+
assert os.path.isfile(optrace_path) and os.path.isfile(qhas_path), (
399+
"Error: Required files not found - either "
400+
f"{os.path.basename(optrace_path)} or {os.path.basename(qhas_path)} is missing."
401+
)
402+
403+
return optrace_path, qhas_path
404+
405+
406+
def generate_optrace(
407+
artifact, soc_id: QcomChipset, adb, pte_path: str, inputs: Tuple[torch.Tensor]
408+
):
409+
"""
410+
Generate optrace and QHAS (QNN HTP Analysis Summary) JSON files.
411+
412+
Args:
413+
artifact (str): Path to the artifact folder.
414+
adb (SimpleADB): An object for communicating with Android device
415+
pte_path (str): The path to the generated PTE file, including the file extension (e.g., model.pte).
416+
inputs (Tuple[torch.Tensor]): The input tensors for the model.
417+
418+
419+
Returns:
420+
dict: A dictionary where keys are the dumped file paths and values are tuples containing the paths
421+
to the generated optrace and QHAS JSON files.
422+
"""
423+
filename, _ = os.path.splitext(pte_path.split(os.sep)[-1])
424+
425+
# Dump compiled binaries
426+
dumpfiles = dump_context_from_pte(pte_path)
427+
428+
# Generate optrace and QHAS
429+
qnn_tool = QnnTool(
430+
artifact,
431+
inputs,
432+
soc_id,
433+
adb,
434+
build_folder=adb.build_path,
435+
workspace=adb.workspace,
436+
)
437+
438+
binaries_trace = {}
439+
for file in dumpfiles:
440+
filename = file.split(os.sep)[-1]
441+
optrace, qhas = qnn_tool.generate_optrace(filename)
442+
binaries_trace[file] = (optrace, qhas)
443+
return binaries_trace

0 commit comments

Comments
 (0)