Qualcomm 디바이스로 프로젝트를 진행하려고 하였는데, 관련 정보가 부족해 여러 가지를 찾아보던 중, Qualcomm AI Hub가 많은 도움을 줄 수 있다는 것을 알게 되었다. 그래서 이 기회를 통해 AI Hub를 사용해 보았고, 그 경험을 정리해보려고 한다.
Qualcomm AI Hub
The platform for on-device AI, with optimized open source and licensed models, or bring your own. Validate performance on real Qualcomm devices.
aihub.qualcomm.com
Qualcomm AI Hub란?
퀄컴 AI 허브는 최적화된 AI 모델과 구체적인 가이드를 제공하여 개발자들뿐만 아니라 누구나 쉽고 빠르게 온디바이스 AI 앱을 개발하고 활용 가능할 수 있도록 만들어 놓은 AI 통합 플랫폼이다.
퀄컴 디바이스들에 최적화된 AI 모델들을 지원하는 플랫폼이며 (25년 3월 기준) AI 모델도 156개 정도 있었으며, 여기 없는 나의 Pre-Trained AI 모델을 원하는 퀄컴 플랫폼에 맞게 Compile, Profiling, Inferencing을 하는 기능도 제공하고 있다고 한다.
Qualcomm AI Hub 프로세스 살펴보기
다음은 퀄컴 AI 허브에서 제공한 MobileNet v2을 Samsung Galaxy S24에서 분석해본 튜토리얼 스크립트인데 단계별로 살펴보았다.
import qai_hub as hub
import torch
from torchvision.models import mobilenet_v2
import requests
import numpy as np
from PIL import Image
# Using pre-trained MobileNet
torch_model = mobilenet_v2(pretrained=True)
torch_model.eval()
# Step 1: Trace model
input_shape = (1, 3, 224, 224)
example_input = torch.rand(input_shape)
traced_torch_model = torch.jit.trace(torch_model, example_input)
# Step 2: Compile model
compile_job = hub.submit_compile_job(
model=traced_torch_model,
device=hub.Device("Samsung Galaxy S24 (Family)"),
input_specs=dict(image=input_shape),
)
# Step 3: Profile on cloud-hosted device
target_model = compile_job.get_target_model()
profile_job = hub.submit_profile_job(
model=target_model,
device=hub.Device("Samsung Galaxy S24 (Family)"),
)
# Step 4: Run inference on cloud-hosted device
sample_image_url = (
"https://qaihub-public-assets.s3.us-west-2.amazonaws.com/apidoc/input_image1.jpg"
)
response = requests.get(sample_image_url, stream=True)
response.raw.decode_content = True
image = Image.open(response.raw).resize((224, 224))
input_array = np.expand_dims(
np.transpose(np.array(image, dtype=np.float32) / 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=target_model,
device=hub.Device("Samsung Galaxy S24 (Family)"),
inputs=dict(image=[input_array]),
)
on_device_output = inference_job.download_output_data()
# Step 5: Post-processing 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
sample_classes = "https://qaihub-public-assets.s3.us-west-2.amazonaws.com/apidoc/imagenet_classes.txt"
response = requests.get(sample_classes, stream=True)
response.raw.decode_content = True
categories = [str(s.strip()) for s in response.raw]
# 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%}")
# Step 6: Download model
target_model = compile_job.get_target_model()
target_model.download("mobilenet_v2.tflite")
https://app.aihub.qualcomm.com/docs/hub/getting_started.html
Getting started — qai-hub documentation
We recommend using Miniconda to manage your python versions and environments. Warning If any of these steps fail with SSL: CERTIFICATE_VERIFY_FAILED errors, you have an SSL interception and traffic inspection tool installed. Ask your IT department for inst
app.aihub.qualcomm.com
필자는 코랩 환경을 통하여 테스트 해보았다.
먼저 코랩에 qai_hub를 인스톨 해주고 퀄 컴 AI 허브에서 발급받은 토큰을 등록한다.
0. 환경 변수와 모델 로드
여기서는 mobilenet_v2를 사용하였다.
Step 1: Trace Model
Step 1에서는 PyTorch 모델을 TorchScript 모델로 변환하여 효율적으로 실행할 수 있게 한다.
torch.jit.trace로 트레이스(tracing)를 수행하여, 모델이 주어진 입력을 처리하는 방법을 기록한다. 이 트레이스를 통해 모델을 TorchScript로 변환한다.
Step 2: Compile Model
Step 2에서는 트레이스된 TorchScript 모델을 Qualcomm AI Hub에서 디바이스에 맞게 컴파일한다.
hub.submit_compile_job는 모델을 특정 디바이스에 최적화하여 컴파일하는 작업을 제출한다. 여기서는 Samsung Galaxy S24 (Family) 디바이스에 맞게 모델을 컴파일 했다.
퀄컴 AI 허브에서 컴파일된 모델을 확인 할 수 있음
Step 3: Profile on Cloud-Hosted Device
모델을 디바이스에서 프로파일링하여 성능을 측정할 수 있다.
링크를 통해 AI허브에서 프로파일링 결과를 확인할 수 있었다.
시각화된 모델의 모습도 볼 수 있음
Step 4: Run Inference on Cloud-Hosted Device
예시 이미지를 사용하여 모델의 예측 결과를 얻어보았다.
- hub.submit_inference_job을 통해 모델에 이미지를 입력으로 넣고 예측을 수행.
- inference_job.download_output_data()를 통해 예측 결과를 다운로드하게 해줌
Step 5: Post-Processing the On-Device Output
후처리 단계에 해당하며 여기서는 예측 결과를 확률로 변환하였다.
ImageNet의 클래스 레이블을 가져와서, 모델의 예측 결과에 따라 상위 5개의 예측을 출력해보았다.
Step 6: Download Model
target_model.download("mobilenet_v2.tflite")는 최종적으로 컴파일된 모델을 다운로드한다. 이 모델은 TensorFlow Lite 형식인 .tflite 파일로 저장된다.
이 과정들을 통해 AI 허브를 통해 갤럭시 S24 울트라에서 mobilenet_v2 모델을 컴파일 하고 동작시켰다.
추가로 다음에서 주석된 코드에 경로를 넣어 로컬 환경에서 트레이닝된 모델을 사용할 수 있다고 한다.
오늘은 Qualcomm Ai Hub를 간단하게 사용하여 보았다. 모델을 Quantization하거나 Export하는 옵션들도 허브에서 지원한다고 하니 아래 문서를 참고하면 더 도움이 될 것 같다.
https://app.aihub.qualcomm.com/docs/hub/getting_started.html
Getting started — qai-hub documentation
We recommend using Miniconda to manage your python versions and environments. Warning If any of these steps fail with SSL: CERTIFICATE_VERIFY_FAILED errors, you have an SSL interception and traffic inspection tool installed. Ask your IT department for inst
app.aihub.qualcomm.com
'Technology Notes' 카테고리의 다른 글
[Docker] 도커와 컨테이너 알아보기 (0) | 2025.02.16 |
---|---|
[Framework] 딥러닝/머신러닝 프레임워크 알아보기 (0) | 2025.02.14 |