추론 실행
특수 하드웨어가 있는 모바일 및 엣지 디바이스에서 모델을 실행하는 것은 참조 환경에서 실행하는 것과 다를 수 있습니다. 예를 들어, PyTorch 구현이 float32 정밀도로 추론을 실행하는 반면, 타깃 하드웨어는 float16 또는 int8을 사용하여 계산을 실행할 수 있습니다. 이는 숫자 불일치와 언더플로 및 오버플로의 가능성으로 이어질 수 있습니다. 이것이 결과에 부정적인 영향을 미치는지 여부는 모델과 데이터 분포에 따라 달라집니다.
추론 작업은 입력 데이터를 업로드하고, 실제 하드웨어에서 추론을 실행하고, 출력 결과를 다운로드하는 방법을 제공합니다. 이러한 결과를 참조 구현과 직접 비교하여 최적화된 모델이 예상대로 작동하는지 여부를 확인할 수 있습니다. 추론은 최적화된 모델에서만 지원됩니다. PyTorch 및 ONNX 와 같은 소스 형식의 모델은 submit_compile_job()
또는 이와 유사한 것으로 컴파일해야 합니다.
추론 작업은 --qairt_version
플래그를 사용하여 특정 Qualcomm® AI Runtime 버전을 선택할 수 있습니다. 지정하지 않으면 버전 선택 에 따라 버전이 선택됩니다.
TensorFlow Lite 모델을 사용한 추론 실행
이 예제에서는 TensorFlow Lite 모델 SqueezeNet10.tflite 를 사용하여 추론을 실행합니다.
import numpy as np
import qai_hub as hub
sample = np.random.random((1, 224, 224, 3)).astype(np.float32)
inference_job = hub.submit_inference_job(
model="SqueezeNet10.tflite",
device=hub.Device("Samsung Galaxy S23 (Family)"),
inputs=dict(x=[sample]),
)
assert isinstance(inference_job, hub.InferenceJob)
inference_job.download_output_data()
추론을 위한 입력은 사전이어야 하며, 여기서 키는 피처의 이름이고 값은 텐서입니다. 텐서는 numpy 배열의 목록이거나 단일 데이터 포인트인 경우 단일 numpy 배열일 수 있습니다.
inference_job
은InferenceJob
의 인스턴스입니다.
Device
객체 목록을 submit_inference_job()
API에 제공하여 여러 추론 작업을 동시에 시작할 수 있습니다.
QNN 모델 라이브러리, DLC 및 컨텍스트 바이너리를 사용한 추론 실행
이 예제는 TorchScript 모델 (mobilenet_v2.pt)을 QNN 모델 라이브러리, QNN DLC 또는 QNN 컨텍스트 바이너리 형식으로 컴파일합니다. 그런 다음 컴파일된 대상 모델로 장치에서 추론을 실행합니다.
import numpy as np
import qai_hub as hub
sample = np.random.random((1, 3, 224, 224)).astype(np.float32)
compile_job = hub.submit_compile_job(
model="mobilenet_v2.pt",
device=hub.Device("Samsung Galaxy S23 (Family)"),
options="--target_runtime qnn_lib_aarch64_android",
input_specs=dict(image=(1, 3, 224, 224)),
)
assert isinstance(compile_job, hub.CompileJob)
inference_job = hub.submit_inference_job(
model=compile_job.get_target_model(),
device=hub.Device("Samsung Galaxy S23 (Family)"),
inputs=dict(image=[sample]),
)
assert isinstance(inference_job, hub.InferenceJob)
import numpy as np
import qai_hub as hub
sample = np.random.random((1, 3, 224, 224)).astype(np.float32)
compile_job = hub.submit_compile_job(
model="mobilenet_v2.pt",
device=hub.Device("Samsung Galaxy S23 (Family)"),
options="--target_runtime qnn_dlc",
input_specs=dict(image=(1, 3, 224, 224)),
)
assert isinstance(compile_job, hub.CompileJob)
inference_job = hub.submit_inference_job(
model=compile_job.get_target_model(),
device=hub.Device("Samsung Galaxy S23 (Family)"),
inputs=dict(image=[sample]),
)
assert isinstance(inference_job, hub.InferenceJob)
import numpy as np
import qai_hub as hub
input_shape = (1, 3, 224, 224)
sample = np.random.random(input_shape).astype(np.float32)
compile_job = hub.submit_compile_job(
model="mobilenet_v2.pt",
device=hub.Device("Samsung Galaxy S24 (Family)"),
options="--target_runtime qnn_context_binary",
input_specs=dict(image=input_shape),
)
assert isinstance(compile_job, hub.CompileJob)
inference_job = hub.submit_inference_job(
model=compile_job.get_target_model(),
device=hub.Device("Samsung Galaxy S24 (Family)"),
inputs=dict(image=[sample]),
)
assert isinstance(inference_job, hub.InferenceJob)
추론 작업을 사용하여 모델 정확도 확인 온디바이스
이 예제는 QNN 모델 라이브러리 온디바이스 의 수치를 검증하는 방법을 보여줍니다.
Reusing the model from the profiling example (mobilenet_v2.pt)
import torch
import qai_hub as hub
device_s23 = hub.Device(name="Samsung Galaxy S23 (Family)")
compile_job = hub.submit_compile_job(
model="mobilenet_v2.pt",
device=device_s23,
input_specs={"x": (1, 3, 224, 224)},
options="--target_runtime qnn_lib_aarch64_android",
)
assert isinstance(compile_job, hub.CompileJob)
on_device_model = compile_job.get_target_model()
우리는 이 최적화된 .so
모델을 사용하고 특정 기기의 입력 데이터로 추론을 실행할 수 있습니다. 이 예에서 사용된 입력 이미지는 다운로드할 수 있습니다 - input_image1.jpg.

import numpy as np
from PIL import Image
# Convert the image to numpy array of shape [1, 3, 224, 224]
image = Image.open("input_image1.jpg").resize((224, 224))
img_array = np.array(image, dtype=np.float32)
# Ensure correct layout (NCHW) and re-scale
input_array = np.expand_dims(np.transpose(img_array / 255.0, (2, 0, 1)), axis=0)
# Run inference using the on-device model on the input image
inference_job = hub.submit_inference_job(
model=on_device_model,
device=device_s23,
inputs=dict(x=[input_array]),
)
assert isinstance(inference_job, hub.InferenceJob)
이 온디바이스 원시 출력을 사용하여 클래스 예측을 생성하고 참조 구현과 비교할 수 있습니다. 이를 위해 imagenet 클래스가 필요합니다 - imagenet_classes.txt.
# Get the on-device output
on_device_output: dict[str, list[np.ndarray]] = inference_job.download_output_data() # type: ignore
# Load the torch model and perform inference
torch_model = torch.jit.load("mobilenet_v2.pt")
torch_model.eval()
# Calculate probabilities for torch model
torch_input = torch.from_numpy(input_array)
torch_output = torch_model(torch_input)
torch_probabilities = torch.nn.functional.softmax(torch_output[0], dim=0)
# Calculate probabilities for the on-device output
output_name = list(on_device_output.keys())[0]
out = on_device_output[output_name][0]
on_device_probabilities = np.exp(out) / np.sum(np.exp(out), axis=1)
# Read the class labels for imagenet
with open("imagenet_classes.txt") as f:
categories = [s.strip() for s in f.readlines()]
# Print top five predictions for the on-device model
print("Top-5 On-Device predictions:")
top5_classes = np.argsort(on_device_probabilities[0], axis=0)[-5:]
for c in reversed(top5_classes):
print(f"{c} {categories[c]:20s} {on_device_probabilities[0][c]:>6.1%}")
# Print top five prediction for torch model
print("Top-5 PyTorch predictions:")
top5_prob, top5_catid = torch.topk(torch_probabilities, 5)
for i in range(top5_prob.size(0)):
print(
f"{top5_catid[i]:4d} {categories[top5_catid[i]]:20s} {top5_prob[i].item():>6.1%}"
)
위 코드는 다음과 같은 결과를 생성합니다:
Top-5 On-Device predictions:
968 cup 71.3%
504 coffee mug 16.4%
967 espresso 7.8%
809 soup bowl 1.3%
659 mixing bowl 1.2%
Top-5 PyTorch predictions:
968 cup 71.4%
504 coffee mug 16.1%
967 espresso 8.0%
809 soup bowl 1.4%
659 mixing bowl 1.2%
온디바이스 결과는 참조 구현과 거의 동일합니다. 이는 모델이 정확성 회귀에 시달리지 않았다는 것을 알려주며 배포되면 예상대로 작동할 것이라는 확신을 줍니다.
이러한 확신을 강화하려면 이를 여러 이미지로 확장하고 KL 발산을 측정하거나 정확도를 비교하는 것과 같은 정량적 요약을 사용하는 것을 고려하세요(레이블이 알려진 경우). 또한 이를 통해 타깃 장치에서 검증하기가 더 쉬워집니다.
이전에 업로드한 데이터 세트 및 모델을 사용하여 추론 실행
AI허브 모델과 유사하게 사용자가 재사용 가능한 데이터를 업로드할 수 있는 API를 제공합니다.
import numpy as np
import qai_hub as hub
data = dict(
x=[
np.random.random((1, 224, 224, 3)).astype(np.float32),
np.random.random((1, 224, 224, 3)).astype(np.float32),
]
)
hub_dataset = hub.upload_dataset(data)
이제 업로드된 데이터 세트를 사용하여 추론 작업을 실행할 수 있습니다. 이 예에서는 SqueezeNet10.tflite 를 사용합니다.
# Submit job
job = hub.submit_inference_job(
model="SqueezeNet10.tflite",
device=hub.Device("Samsung Galaxy S23 (Family)"),
inputs=hub_dataset,
)