| 66 | |
| 67 | |
| 68 | def generate_context_binary( |
| 69 | module: torch.nn.Module, |
| 70 | inputs: Dict[str, torch.Tensor], |
| 71 | quantized: bool, |
| 72 | artifact_dir: str, |
| 73 | ): |
| 74 | # we also expect clang showing in PATH or context may fail to generate |
| 75 | qnn_sdk = os.environ.get("QNN_SDK_ROOT", None) |
| 76 | ndk = os.environ.get("ANDROID_NDK_ROOT", None) |
| 77 | assert qnn_sdk, "QNN_SDK_ROOT was not found in environment variable" |
| 78 | assert ndk, "ANDROID_NDK_ROOT was not found in environment variable" |
| 79 | |
| 80 | inputs_tup = tuple(inputs.values()) |
| 81 | jit_module = torch.jit.trace(module, inputs_tup) |
| 82 | torch.jit.save(jit_module, f"{artifact_dir}/jit_module.pt") |
| 83 | |
| 84 | # input data |
| 85 | if quantized: |
| 86 | input_list = [] |
| 87 | for name, data in inputs.items(): |
| 88 | file_name = f"{artifact_dir}/{name}.raw" |
| 89 | data.detach().numpy().tofile(file_name) |
| 90 | input_list.append(file_name) |
| 91 | |
| 92 | with open(f"{artifact_dir}/input_list.txt", "w") as f: |
| 93 | f.write(" ".join(input_list)) |
| 94 | |
| 95 | # flow of qnn tools |
| 96 | target = "x86_64-linux-clang" |
| 97 | inputs_str = [ |
| 98 | f"-d '{k}' {str(tuple(v.shape)).replace(' ', '')[1:-1]}" |
| 99 | for k, v in inputs.items() |
| 100 | ] |
| 101 | cmds = [ |
| 102 | # setup qnn env |
| 103 | f"source {qnn_sdk}/bin/envsetup.sh;" |
| 104 | # qnn-pytorch-converter |
| 105 | f"{qnn_sdk}/bin/{target}/qnn-pytorch-converter", |
| 106 | f"-i {artifact_dir}/jit_module.pt", |
| 107 | *inputs_str, |
| 108 | f"--input_list {artifact_dir}/input_list.txt" if quantized else "", |
| 109 | "--preserve_io", |
| 110 | f"-o {artifact_dir}/model.cpp;", |
| 111 | # qnn-model-lib-generator |
| 112 | f"{qnn_sdk}/bin/{target}/qnn-model-lib-generator", |
| 113 | f"-c {artifact_dir}/model.cpp", |
| 114 | f"-t {target}", |
| 115 | "-l model", |
| 116 | f"-o {artifact_dir}/model_libs;", |
| 117 | # qnn-context-binary-generator |
| 118 | f"{qnn_sdk}/bin/{target}/qnn-context-binary-generator", |
| 119 | f"--model {artifact_dir}/model_libs/{target}/libmodel.so", |
| 120 | f"--backend {qnn_sdk}/lib/{target}/libQnnHtp.so", |
| 121 | "--binary_file model_ctx", |
| 122 | f"--output_dir {artifact_dir};", |
| 123 | ] |
| 124 | result = subprocess.run( |
| 125 | " ".join(cmds), |