|
| 1 | +import json |
1 | 2 | import os
|
| 3 | +import re |
2 | 4 | import shutil
|
| 5 | +import subprocess |
3 | 6 | import tempfile
|
| 7 | +from pathlib import Path |
| 8 | +from typing import Tuple |
4 | 9 |
|
5 | 10 | import executorch.backends.qualcomm.python.PyQnnWrapperAdaptor as PyQnnWrapper
|
6 | 11 | 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 | + |
7 | 16 | from graphviz import Digraph
|
8 | 17 |
|
9 | 18 |
|
@@ -180,3 +189,255 @@ def draw(self):
|
180 | 189 | dot_file = os.path.join(temp_directory, f"{self.filename}")
|
181 | 190 | dot_dest_file = os.path.join(".", f"{self.filename}.dot")
|
182 | 191 | 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