Skip to content

Qualcomm AI Engine Direct - GA Model Enablement (deit) #11065

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3679,6 +3679,41 @@ def test_conv_former(self):
self.assertGreaterEqual(msg["top_1"], 60)
self.assertGreaterEqual(msg["top_5"], 80)

def test_deit(self):
if not self.required_envs([self.image_dataset]):
self.skipTest("missing required envs")
cmds = [
"python",
f"{self.executorch_root}/examples/qualcomm/oss_scripts/deit.py",
"--dataset",
self.image_dataset,
"--artifact",
self.artifact_dir,
"--build_folder",
self.build_folder,
"--device",
self.device,
"--model",
self.model,
"--ip",
self.ip,
"--port",
str(self.port),
]
if self.host:
cmds.extend(["--host", self.host])

p = subprocess.Popen(cmds, stdout=subprocess.DEVNULL)
with Listener((self.ip, self.port)) as listener:
conn = listener.accept()
p.communicate()
msg = json.loads(conn.recv())
if "Error" in msg:
self.fail(msg["Error"])
else:
self.assertGreaterEqual(msg["top_1"], 75)
self.assertGreaterEqual(msg["top_5"], 90)

def test_dino_v2(self):
if not self.required_envs([self.image_dataset]):
self.skipTest("missing required envs")
Expand Down
147 changes: 147 additions & 0 deletions examples/qualcomm/oss_scripts/deit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# Copyright (c) Qualcomm Innovation Center, Inc.
# All rights reserved
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

import getpass
import json
import os
from multiprocessing.connection import Client

import numpy as np
import torch
from executorch.backends.qualcomm._passes.qnn_pass_manager import (
get_capture_program_passes,
)
from executorch.backends.qualcomm.quantizer.quantizer import QuantDtype
from executorch.examples.qualcomm.utils import (
build_executorch_binary,
get_imagenet_dataset,
make_output_dir,
parse_skip_delegation_node,
setup_common_args_and_variables,
SimpleADB,
topk_accuracy,
)
from transformers import AutoConfig, AutoModelForImageClassification


def get_instance():
module = (
AutoModelForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224")
.eval()
.to("cpu")
)

return module


def main(args):
skip_node_id_set, skip_node_op_set = parse_skip_delegation_node(args)

os.makedirs(args.artifact, exist_ok=True)
config = AutoConfig.from_pretrained("facebook/deit-base-distilled-patch16-224")
data_num = 100
height = config.image_size
width = config.image_size
inputs, targets, input_list = get_imagenet_dataset(
dataset_path=f"{args.dataset}",
data_size=data_num,
image_shape=(height, width),
crop_size=(height, width),
)

# Get the Deit model.
model = get_instance()
pte_filename = "deit_qnn"

# lower to QNN
passes_job = get_capture_program_passes()
build_executorch_binary(
model,
inputs[0],
args.model,
f"{args.artifact}/{pte_filename}",
dataset=inputs,
skip_node_id_set=skip_node_id_set,
skip_node_op_set=skip_node_op_set,
quant_dtype=QuantDtype.use_8a8w,
passes_job=passes_job,
shared_buffer=args.shared_buffer,
)

if args.compile_only:
return

workspace = f"/data/local/tmp/{getpass.getuser()}/executorch/{pte_filename}"
pte_path = f"{args.artifact}/{pte_filename}.pte"

adb = SimpleADB(
qnn_sdk=os.getenv("QNN_SDK_ROOT"),
build_path=f"{args.build_folder}",
pte_path=pte_path,
workspace=workspace,
device_id=args.device,
host_id=args.host,
soc_model=args.model,
)
adb.push(inputs=inputs, input_list=input_list)
adb.execute()

# collect output data
output_data_folder = f"{args.artifact}/outputs"
make_output_dir(output_data_folder)

adb.pull(output_path=args.artifact)

# top-k analysis
predictions = []
for i in range(data_num):
predictions.append(
np.fromfile(
os.path.join(output_data_folder, f"output_{i}_0.raw"), dtype=np.float32
)
)

k_val = [1, 5]
topk = [topk_accuracy(predictions, targets, k).item() for k in k_val]
if args.ip and args.port != -1:
with Client((args.ip, args.port)) as conn:
conn.send(json.dumps({f"top_{k}": topk[i] for i, k in enumerate(k_val)}))
else:
for i, k in enumerate(k_val):
print(f"top_{k}->{topk[i]}%")


if __name__ == "__main__":
parser = setup_common_args_and_variables()
parser.add_argument(
"-a",
"--artifact",
help="path for storing generated artifacts and output by this example. Default ./deit_qnn",
default="./deit_qnn",
type=str,
)

parser.add_argument(
"-d",
"--dataset",
help=(
"path to the validation folder of ImageNet dataset. "
"e.g. --dataset imagenet-mini/val "
"for https://www.kaggle.com/datasets/ifigotin/imagenetmini-1000)"
),
type=str,
required=True,
)

args = parser.parse_args()
try:
main(args)
except Exception as e:
if args.ip and args.port != -1:
with Client((args.ip, args.port)) as conn:
conn.send(json.dumps({"Error": str(e)}))
else:
raise Exception(e)
Loading