Metadata-Version: 2.2
Name: qnnruntime
Version: 2.48.0.2
Summary: Direct Python runtime for Qualcomm QNN context binaries
Requires-Python: >=3.9
Requires-Dist: numpy>=1.23
Description-Content-Type: text/markdown

# qnnruntime

`qnnruntime` loads one QNN Context Binary and executes it directly from NumPy
memory. It does not invoke `qnn-net-run` or create raw input/output files.

## Build on an aarch64 target

```bash
python3 -m pip install --user build
python3 -m build --wheel -Ccmake.args=-DQNN_SDK_ROOT=/opt/qairt/2.48.0
```

The QNN SDK is deliberately **not** included in the wheel. At runtime, make its
host libraries discoverable, for example:

```bash
export LD_LIBRARY_PATH=/data/local/tmp/qnn2.48.0:$LD_LIBRARY_PATH
# QNN uses a semicolon-separated DSP search path on this Linux target.
export ADSP_LIBRARY_PATH='/data/local/tmp/qnn2.48.0;/usr/lib/rfsa/adsp;/vendor/lib/rfsa/adsp;/vendor/dsp/cdsp'
```

## Use

```python
import numpy as np
import qnnruntime as qr

session = qr.InferenceSession("model.ctx.bin")
print(session.get_inputs())
outputs = session.run(None, {"images": np.zeros((1, 640, 640, 3), np.float32)})
```

`InferenceSession` is synchronous and supports a single, static-shape graph.
By default, `run()` accepts float arrays and returns `float32`. Scalar
scale/offset QNN tensors are quantized and dequantized from Context Binary
metadata automatically. Inputs must be C-contiguous NumPy arrays whose names
and shapes match the Context Binary metadata.

For advanced callers that already own the QNN-native buffers, `run_raw()` (or
`run(..., raw=True)`) performs no conversion and requires the exact metadata
dtype:

```python
raw_input = np.zeros(session.get_inputs()[0].shape, dtype=np.uint16)
raw_output = session.run_raw(None, {"images": raw_input})  # uint16 output
```

Automatic conversion intentionally rejects per-axis quantization and
non-quantized integer model inputs: their semantics are model-specific, so use
the raw API rather than applying an unsafe implicit conversion.

HTP uses every core reported by `QnnDevice_getPlatformInfo()` by default. For a
Context Binary prepared for a specific subset (for example an IQ10 3-core
graph), choose it explicitly:

```python
session = qr.InferenceSession("model.ctx.bin", num_cores=3)
```

HTP sessions request the QNN `burst` profile by default. On targets that
support direct HTP performance voting this selects low latency:

```python
session = qr.InferenceSession(
    "model.ctx.bin", performance_profile="burst", rpc_control_latency_us=100
)
```

`burst` votes Turbo core and bus clocks, disables HTP sleep, and uses the given
RPC control latency. It has higher power and thermal cost. If a device image
rejects direct HTP power votes, qnnruntime falls back to the backend default;
use `balanced` to skip the request explicitly.

## Private self-contained wheel for all bundled HTP architectures

The QAIRT license permits object-code redistribution only when incorporated in
your application; it does not permit standalone redistribution. Confirm that
your distribution is covered before enabling this option.

The wheel bundles the CPU and HTP host libraries, all HTP DSP skeletons, and
QNN catalogs for V68/V69/V73/V75/V79/V81 Context Binaries. GPU, LPAI, SNPE,
GenAI and profiling libraries are intentionally excluded. Build on the aarch64
target with the exact QNN runtime used to create/run the Context Binary:

```bash
python3 -m build --wheel --no-isolation \
  -Ccmake.args=-DQNN_SDK_ROOT=/path/to/qairt-sdk \
  -Ccmake.args=-DQNN_BUNDLE_RUNTIME=ON \
  -Ccmake.args=-DQNN_RUNTIME_DIR=/data/local/tmp/qnn2.48.0 \
  -Ccmake.args=-DQNN_DSP_RUNTIME_DIR=/data/local/tmp/qnn2.48.0
```

The resulting private wheel places its QNN runtime under `qnnruntime/.libs`.
`qnnruntime` loads host libraries from there and prepends that directory to
`ADSP_LIBRARY_PATH`. HTP additionally requires the board's Qualcomm FastRPC
transport, `libcdsprpc.so` (provided by AidLux under `/usr/lib`); it is a
platform component and is not distributed in the QNN SDK or this wheel.

## YOLOv5 helper and result parity

`qnnruntime.contrib.yolov5` is an optional, NumPy-only application helper. It
uses the current target demo's top-left square padding, BGR-to-RGB conversion,
bilinear resize, `float / 255`, and QNN scalar scale/offset quantization.
It also dequantizes `(q + offset) * scale` and performs class-aware NMS for a
standard `(1, N, 85)` YOLOv5 output. `InferenceSession` remains model-neutral.

For results identical to AidLite, compare using **the same Context Binary**,
input image, pad convention, RGB order, resize interpolation, quantization and
confidence/IoU thresholds. The helper makes these choices explicit. It is not
valid to compare a QCS8550 W8A16 Context Binary with a different QNN version or
another quantization model and expect bit-identical output.

```python
from qnnruntime.contrib.yolov5 import preprocess_square_rgb, yolov5_detections

input_data, _ = preprocess_square_rgb(bgr_image, session.get_inputs()[0])
raw = session.run(None, {session.get_inputs()[0].name: input_data})[0]
detections = yolov5_detections(raw, session.get_outputs()[0])
```

## Repeatable build and release

The checked-in [build script](scripts/build_wheel.sh) builds one wheel for the
current aarch64 Python ABI. It needs a licensed QAIRT SDK only on the build
machine; the resulting private wheel contains the selected QNN runtime bundle.

```bash
export QNN_SDK_ROOT=/opt/qairt/2.48.0
export QNN_RUNTIME_DIR=/data/local/tmp/qnn2.48.0
export PYTHON_BIN=python3.12
bash scripts/build_wheel.sh
```

[The GitLab CI pipeline](.gitlab-ci.yml) uses self-hosted ARM64 runners labelled
`qnn-aarch64-py310` and `qnn-aarch64-py312`. Set `QNN_SDK_ROOT`,
`QNN_RUNTIME_DIR`, optional `QNN_DSP_RUNTIME_DIR`, and a matching
`QNN_SMOKE_MODEL` as protected GitLab CI/CD variables. Every pipeline retains
the ABI-specific wheel artifacts for one year; pushing a `v*` tag uploads the
wheels as GitLab Release attachments. No GitLab PyPI Package Registry is used.

### x86 GitLab Runner cross-build

The default GitLab pipeline uses Docker Buildx plus QEMU, so an x86_64 Docker
runner tagged `qnn-x86-docker` produces Linux aarch64 wheels for CPython 3.9,
3.10, 3.11, 3.12 and 3.13. It downloads QAIRT 2.36, 2.40 and 2.48 directly
from Qualcomm Software Center and publishes them under the single distribution
name `qnnruntime`. Versions use
`<QNN-major>.<QNN-minor>.<QNN-patch>.<qnnruntime-revision>`:

```bash
# Exact, reproducible QNN 2.48 bundle revision.
pip install 'qnnruntime==2.48.0.2'

# Latest qnnruntime revision for QNN 2.48.
pip install -U 'qnnruntime==2.48.*'
```

The current bundles are `2.36.4.2`, `2.40.0.2`, and `2.48.0.2`. Install only one,
as all expose the Python import name `qnnruntime`. The full QAIRT SDK build is
recorded by the CI matrix. It uses
[`docker/Dockerfile.cross-aarch64`](docker/Dockerfile.cross-aarch64), based on
the aarch64 manylinux 2.34 image. QAIRT's OE Linux libraries require glibc
2.34, so the published wheels are tagged `manylinux_2_34_aarch64`. The runner
must permit privileged Docker (`docker:dind` and `tonistiigi/binfmt`).

The `qnn-x86-docker` GitLab Runner must use the Docker executor with
`privileged = true`; Buildx needs that privilege to install the `arm64` binfmt
handler. The first build downloads each multi-gigabyte QAIRT archive; BuildKit
caches it at `/var/cache/qnn-sdk` for subsequent builds. The `qnn-publish`
runner only needs network access to GitLab.

The SDK is passed as Docker BuildKit named contexts, not committed to Git and
not included in GitLab logs. A wheel is aarch64 binary, so Docker builds it but
cannot usefully test HTP on an ordinary x86 machine. Install the artifact on a
board and run `scripts/smoke_test.py` against that board's matching Context
Binary as the hardware acceptance step. On a `v0.2.0` Git tag, the pipeline
sets the wheel version to `0.2.0`; ordinary branch pipelines retain the source
version and only publish downloadable artifacts.
