In this tutorial, we walk through an end-to-end workflow using Qualcomm AI Hub Models. We begin by setting up the required package, exploring the available model collection, and loading MobileNet-V2 for local PyTorch inference. We address an important input-shape issue by converting NHWC image tensors to the NCHW format expected by the model. We then run inference on both the model's built-in sample input and a real image, inspect top predictions, execute the official CLI demo, and extend the workflow with a YOLOv7 object detection example. Additionally, we include an optional section on compiling, profiling, and running models on a real Qualcomm device using an API token.
Setup and Utility Functions
We start by importing libraries and defining a helper to install packages directly in Colab. We install qai_hub_models, create an output directory, and disable gradient tracking for inference. We also define a to_nchw() function to convert input tensors to channel-first format.
import subprocess, sys, os, glob, textwrap, traceback
import numpy as np, torch
from PIL import Image
import matplotlib.pyplot as plt
def pip_install(*pkgs):
subprocess.run([sys.executable, "-m", "pip", "install", "-q", *pkgs], check=True)
pip_install("qai_hub_models")
OUT_DIR = "/content/qaihm_out"; os.makedirs(OUT_DIR, exist_ok=True)
torch.set_grad_enabled(False)
def to_nchw(value):
arr = value[0] if isinstance(value, (list, tuple)) else value
t = torch.from_numpy(np.asarray(arr, dtype=np.float32))
if t.ndim == 3:
t = t.unsqueeze(0)
if t.ndim == 4 and t.shape[1] != 3 and t.shape[-1] == 3:
t = t.permute(0, 3, 1, 2).contiguous()
return t
Discovering Models and Loading MobileNet-V2
We list all available Qualcomm AI Hub model IDs and load the pretrained MobileNet-V2 model. We inspect its input specification and prepare ImageNet class labels for top-5 predictions.
import pkgutil, qai_hub_models.models as _m
model_ids = sorted(n for _, n, p in pkgutil.iter_modules(_m.__path__)
if p and not n.startswith("_"))
print(f">>> {len(model_ids)} models available. First 40:\n")
print(textwrap.fill(", ".join(model_ids[:40]), 100), "\n")
from qai_hub_models.models.mobilenet_v2 import Model as MobileNetV2
model = MobileNetV2.from_pretrained().eval()
spec = model.get_input_spec()
input_name = list(spec.keys())[0]
print(">>> Input:", input_name, spec[input_name].shape, spec[input_name].dtype)
from torchvision.models import MobileNet_V2_Weights
IMAGENET_CLASSES = MobileNet_V2_Weights.IMAGENET1K_V1.meta["categories"]
def top5(logits):
if logits.ndim == 1: logits = logits.unsqueeze(0)
probs = torch.softmax(logits, dim=1)[0]
conf, idx = probs.topk(5)
return [(IMAGENET_CLASSES[i], float(c)) for c, i in zip(conf, idx)]
Running Inference and Deploying to Device
We proceed to run inference on sample inputs and a real image, then execute the official Qualcomm AI Hub CLI demo. For object detection, we integrate YOLOv7. Finally, we demonstrate compiling and running the model on a Qualcomm device using an API token, showcasing hardware-aware deployment.