|
| 1 | +# Copyright (c) Qualcomm Innovation Center, Inc. |
| 2 | +# All rights reserved |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import getpass |
| 8 | +import json |
| 9 | +import os |
| 10 | +from multiprocessing.connection import Client |
| 11 | + |
| 12 | +import evaluate |
| 13 | +import numpy as np |
| 14 | +import torch |
| 15 | + |
| 16 | +from executorch.backends.qualcomm._passes.qnn_pass_manager import ( |
| 17 | + get_capture_program_passes, |
| 18 | +) |
| 19 | +from executorch.backends.qualcomm.quantizer.quantizer import QuantDtype |
| 20 | + |
| 21 | +from executorch.examples.qualcomm.utils import ( |
| 22 | + build_executorch_binary, |
| 23 | + get_masked_language_model_dataset, |
| 24 | + make_output_dir, |
| 25 | + parse_skip_delegation_node, |
| 26 | + setup_common_args_and_variables, |
| 27 | + SimpleADB, |
| 28 | +) |
| 29 | +from transformers import AutoModelForMaskedLM, AutoTokenizer |
| 30 | + |
| 31 | + |
| 32 | +def get_instance(args): |
| 33 | + module = AutoModelForMaskedLM.from_pretrained("xlm-roberta-base").eval() |
| 34 | + return module |
| 35 | + |
| 36 | + |
| 37 | +def main(args): |
| 38 | + skip_node_id_set, skip_node_op_set = parse_skip_delegation_node(args) |
| 39 | + |
| 40 | + os.makedirs(args.artifact, exist_ok=True) |
| 41 | + data_size = 100 |
| 42 | + |
| 43 | + tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base") |
| 44 | + inputs, targets, input_list = get_masked_language_model_dataset( |
| 45 | + args.dataset, tokenizer, data_size |
| 46 | + ) |
| 47 | + |
| 48 | + # Get the Roberta model. |
| 49 | + model = get_instance(args) |
| 50 | + pte_filename = "roberta_qnn" |
| 51 | + |
| 52 | + # lower to QNN |
| 53 | + passes_job = get_capture_program_passes() |
| 54 | + build_executorch_binary( |
| 55 | + model, |
| 56 | + inputs[0], |
| 57 | + args.model, |
| 58 | + f"{args.artifact}/{pte_filename}", |
| 59 | + dataset=inputs, |
| 60 | + skip_node_id_set=skip_node_id_set, |
| 61 | + skip_node_op_set=skip_node_op_set, |
| 62 | + quant_dtype=QuantDtype.use_16a8w, |
| 63 | + passes_job=passes_job, |
| 64 | + shared_buffer=args.shared_buffer, |
| 65 | + ) |
| 66 | + |
| 67 | + if args.compile_only: |
| 68 | + return |
| 69 | + |
| 70 | + workspace = f"/data/local/tmp/{getpass.getuser()}/executorch/{pte_filename}" |
| 71 | + pte_path = f"{args.artifact}/{pte_filename}.pte" |
| 72 | + |
| 73 | + adb = SimpleADB( |
| 74 | + qnn_sdk=os.getenv("QNN_SDK_ROOT"), |
| 75 | + build_path=f"{args.build_folder}", |
| 76 | + pte_path=pte_path, |
| 77 | + workspace=workspace, |
| 78 | + device_id=args.device, |
| 79 | + host_id=args.host, |
| 80 | + soc_model=args.model, |
| 81 | + ) |
| 82 | + output_data_folder = f"{args.artifact}/outputs" |
| 83 | + make_output_dir(output_data_folder) |
| 84 | + |
| 85 | + # demo |
| 86 | + mask_token = tokenizer.mask_token |
| 87 | + text = f"Hello I'm a {mask_token} model." |
| 88 | + sample_input = tokenizer( |
| 89 | + text, |
| 90 | + return_tensors="pt", |
| 91 | + padding="max_length", |
| 92 | + max_length=inputs[0][0].shape[1], |
| 93 | + ) |
| 94 | + sample_input["input_ids"] = sample_input["input_ids"].to(torch.int32) |
| 95 | + sample_input["attention_mask"] = sample_input["attention_mask"].to(torch.float32) |
| 96 | + sample_input = tuple(sample_input.values()) |
| 97 | + golden = model(*sample_input)[0] |
| 98 | + adb.push(inputs=[sample_input], input_list="input_0_0.raw input_0_1.raw\n") |
| 99 | + adb.execute() |
| 100 | + adb.pull(output_path=args.artifact) |
| 101 | + |
| 102 | + print(f"input: {tokenizer.batch_decode(sample_input[0])}") |
| 103 | + print(f"golden output: {tokenizer.batch_decode(golden.argmax(axis=2))}") |
| 104 | + predictions = np.fromfile( |
| 105 | + os.path.join(output_data_folder, "output_0_0.raw"), dtype=np.float32 |
| 106 | + ).reshape([1, inputs[0][0].shape[1], -1]) |
| 107 | + print(f"QNN output: {tokenizer.batch_decode(predictions.argmax(axis=2))}") |
| 108 | + |
| 109 | + # accuracy analysis |
| 110 | + adb.push(inputs=inputs, input_list=input_list) |
| 111 | + adb.execute() |
| 112 | + adb.pull(output_path=args.artifact) |
| 113 | + goldens, predictions = [], [] |
| 114 | + for i in range(len(inputs)): |
| 115 | + indice = [i for i, x in enumerate(targets[i]) if x != -100] |
| 116 | + goldens.extend(targets[i][indice].tolist()) |
| 117 | + prediction = ( |
| 118 | + np.fromfile( |
| 119 | + os.path.join(output_data_folder, f"output_{i}_0.raw"), dtype=np.float32 |
| 120 | + ) |
| 121 | + .reshape([1, inputs[0][0].shape[1], -1]) |
| 122 | + .argmax(axis=-1) |
| 123 | + ) |
| 124 | + predictions.extend(prediction[0, indice].tolist()) |
| 125 | + metric = evaluate.load("accuracy") |
| 126 | + results = metric.compute(predictions=predictions, references=goldens) |
| 127 | + if args.ip and args.port != -1: |
| 128 | + with Client((args.ip, args.port)) as conn: |
| 129 | + conn.send(json.dumps({"accuracy": results["accuracy"]})) |
| 130 | + else: |
| 131 | + print(f"accuracy: {results['accuracy']}") |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + parser = setup_common_args_and_variables() |
| 136 | + parser.add_argument( |
| 137 | + "-a", |
| 138 | + "--artifact", |
| 139 | + help="path for storing generated artifacts and output by this example. Default ./Roberta_qnn", |
| 140 | + default="./Roberta_qnn", |
| 141 | + type=str, |
| 142 | + ) |
| 143 | + parser.add_argument( |
| 144 | + "-d", |
| 145 | + "--dataset", |
| 146 | + help=( |
| 147 | + "path to the validation text. " |
| 148 | + "e.g. --dataset wikisent2.txt " |
| 149 | + "for https://www.kaggle.com/datasets/mikeortman/wikipedia-sentences" |
| 150 | + ), |
| 151 | + type=str, |
| 152 | + required=True, |
| 153 | + ) |
| 154 | + |
| 155 | + args = parser.parse_args() |
| 156 | + try: |
| 157 | + main(args) |
| 158 | + except Exception as e: |
| 159 | + if args.ip and args.port != -1: |
| 160 | + with Client((args.ip, args.port)) as conn: |
| 161 | + conn.send(json.dumps({"Error": str(e)})) |
| 162 | + else: |
| 163 | + raise Exception(e) |
0 commit comments