Bắt đầu

Xuất Rockchip RKNN

RKNN là định dạng model của NPU trên các bộ xử lý Rockchip như RK3588 và RK3566. Xuất model Ultralytics YOLO26 bằng format="rknn" sẽ tạo thư mục yolo26n_rknn_model/ chứa tệp .rknn được xây dựng cho một chip Rockchip; bạn chọn chip bằng đối số name. Tệp sử dụng độ chính xác FP16 hoặc INT8.

Tổng quan nhanh#

Thuộc tínhChi tiết
Đối số formatrknn
Đầu rayolo26n_rknn_model/, một thư mục chứa yolo26n-rk3588.rknn và metadata.yaml; các bản xuất INT8 của model detect, segment, pose và OBB bổ sung tail.onnx
Chạy trênNPU của một chip Rockchip cho mỗi lần xuất: RK3588, RK3576, RK3566, RK3568, RK3562, RK2118, RV1126B, RV1103, RV1106, RV1103B hoặc RV1106B; xem Chip mục tiêu
RuntimeRKNN Toolkit Lite2 (gói Python rknn-toolkit-lite2) trên thiết bị Rockchip
PrecisionFP16 (mặc định) và INT8; chỉ hỗ trợ INT8 trên RV1103, RV1106, RV1103B và RV1106B. Không có bản xuất FP32. YOLO26n cho RK3588 có dung lượng 7.4 MB ở FP16 và 4.3 MB ở INT8
Máy exportLinux x86-64 với Python 3.12 trở xuống. Xuất trên PC rồi sao chép thư mục đã xuất sang thiết bị Rockchip
Export trên cloud

Ultralytics Platform có thể xuất model đã huấn luyện sang RKNN cho chip Rockchip bạn chọn, vì vậy bạn không cần môi trường xuất cục bộ.

Bắt đầu nhanh#

Cài gói Ultralytics trong một môi trường ảo riêng trên máy Linux x86-64, cùng với các phiên bản protobuf và numpy mà bộ công cụ RKNN yêu cầu:

pip install ultralytics "protobuf<7" "numpy<2.4"

Lần xuất đầu tiên sẽ cài đặt onnx, onnxslim, onnxruntime và rknn-toolkit2 cùng các phần phụ thuộc nếu chúng chưa có. Với pip install ultralytics thông thường, lần xuất đầu tiên cũng thay thế numpy, protobuf và setuptools nếu phiên bản của chúng nằm ngoài các phạm vi bên dưới, vì vậy hãy dùng một môi trường riêng. Khi cần thay thế protobuf hoặc numpy, lần xuất đó sẽ thất bại, còn lần xuất tiếp theo trong một tiến trình mới sẽ thành công. Các yêu cầu phiên bản của quá trình xuất như sau:

PackagePhiên bản yêu cầu
Python3.12 trở xuống, là phiên bản mới nhất mà rknn-toolkit2 2.3.2 có bản dựng
rknn-toolkit22.3.2, bản phát hành duy nhất trên PyPI trong phạm vi yêu cầu (2.3.2 trở lên và dưới 2.5)
onnx1.16.1 trở lên và dưới 1.19.0
numpydưới 2.4
protobufdưới 7
setuptoolsdưới 82

Để xem các phương thức cài đặt khác, hãy tham khảo hướng dẫn cài đặt. Sau đó, xuất model trên PC, sao chép thư mục đã xuất sang thiết bị Rockchip và tải model lên thiết bị để chạy inference hoặc đánh giá độ chính xác.

Export
from ultralytics import YOLO

# Nạp model YOLO26
model = YOLO("yolo26n.pt")

# # Xuất model sang định dạng RKNN cho RK3588 ở FP16
model.export(format="rknn", name="rk3588")  # creates 'yolo26n_rknn_model/'

# # Hoặc xuất model RKNN đã lượng tử hóa INT8 bằng dữ liệu hiệu chuẩn
model.export(format="rknn", name="rk3588", quantize=8, data="coco8.yaml")  # creates 'yolo26n_rknn_model/'

Cả hai lần xuất đều ghi vào cùng thư mục yolo26n_rknn_model/, vì vậy lần xuất thứ hai sẽ thay thế lần đầu. Predict và Validate chỉ chạy trên thiết bị Rockchip:

Dự đoán
from ultralytics import YOLO

# # Tải model RKNN đã xuất lên thiết bị Rockchip
model = YOLO("yolo26n_rknn_model")

# Chạy suy luận
results = model("https://ultralytics.com/images/bus.jpg")
Xác thực
from ultralytics import YOLO

# # Tải model RKNN đã xuất lên thiết bị Rockchip
model = YOLO("yolo26n_rknn_model")

# # Đánh giá độ chính xác trên bộ dữ liệu COCO8
metrics = model.val(data="coco8.yaml")

Các tác vụ được hỗ trợ#

Quá trình xuất RKNN hỗ trợ cả bảy tác vụ Ultralytics với các model YOLOv8, YOLO11 và YOLO26: detection, segmentation, segmentation ngữ nghĩa, ước lượng độ sâu, phân loại, ước lượng pose và OBB. Segmentation ngữ nghĩa và ước lượng độ sâu chỉ có trên YOLO26, dòng model duy nhất có các head này.

Các tham số xuất model#

Đối sốKiểuMặc địnhMô tả
formatstr'rknn'Định dạng đích của model đã xuất, xác định khả năng tương thích với nhiều môi trường triển khai.
namestr'rk3588'Chip Rockchip mà model được xây dựng cho, viết hoa hoặc viết thường. Xem Chip mục tiêu.
imgszint hoặc tuple640Kích thước ảnh đầu vào của model: một số nguyên cho ảnh vuông hoặc một tuple (height, width). Nếu không truyền tham số này, quá trình xuất sẽ dùng kích thước mà checkpoint được huấn luyện. Các checkpoint YOLO26 chính thức sử dụng 640 cho model detect, segment, pose và model ngữ nghĩa được tiền huấn luyện trên ADE20K; 1024 cho model OBB và model ngữ nghĩa được tiền huấn luyện trên Cityscapes; 768 cho tác vụ depth; và 224 cho classify.
quantizeint hoặc strNoneĐộ chính xác: 16 hoặc không đặt sẽ tạo bản dựng FP16, còn 8 tạo bản dựng INT8 được hiệu chuẩn trên data. Với các chip chỉ hỗ trợ INT8, không đặt tham số sẽ tạo bản dựng INT8 và 16 sẽ gây lỗi. 32 sẽ gây lỗi, và không thể xuất checkpoint được huấn luyện bằng quantize=8 sang RKNN; xem Giới hạn và khắc phục sự cố. Thay thế các cờ half/int8 đã bị khai tử.
datastrNoneFile YAML của dataset dùng để hiệu chuẩn INT8; với phân loại, thay vào đó cần thư mục dataset hoặc tên dataset tích hợp sẵn. Hiệu chuẩn dùng split val trừ khi đặt split. Nếu không cung cấp quantize=8, Ultralytics dùng dataset mặc định nhỏ cho tác vụ của model, chẳng hạn coco8.yaml cho phát hiện.
fractionfloat, int hoặc list1.0Tập con hiệu chuẩn: tỷ lệ, số lượng ảnh (số nguyên lớn hơn 1) hoặc danh sách [train, val, test]; mục nhập của tập chia hiệu chuẩn sẽ được sử dụng.
batchint1Kích thước batch của model đã xuất, được cố định trong shape đầu vào.
simplifyboolTrueĐơn giản hóa đồ thị ONNX trung gian bằng onnxslim.
opsetintNonePhiên bản opset ONNX của đồ thị ONNX trung gian. Nếu không đặt, sẽ dùng 19; các giá trị cao hơn sẽ được giảm xuống 19.
nmsbool, không bắt buộcNoneModel RKNN luôn trả về dự đoán thô để áp dụng NMS bên ngoài. Head không cần NMS (False) và NMS tích hợp (True) không khả dụng; xem Giới hạn và khắc phục sự cố.
devicestrNoneThiết bị dùng để trace đồ thị ONNX trung gian: cpu (mặc định) hoặc 0 cho GPU CUDA.

Để biết các đối số dùng chung cho mọi định dạng, hãy xem tài liệu chế độ Export.

Chip mục tiêu#

Tệp .rknn được xây dựng cho một chip; name dùng để chọn chip đó. Kích thước bên dưới áp dụng cho model detection YOLO26n được xuất ở imgsz=640, khi quantize không được đặt:

nameĐộ chính xácKhi không đặt quantize, bản dựng sử dụngTệp YOLO26nKích thước
rk3588FP16, INT8FP16yolo26n-rk3588.rknn7.4 MB
rk3576FP16, INT8FP16yolo26n-rk3576.rknn10.5 MB
rk3566FP16, INT8FP16yolo26n-rk3566.rknn6.8 MB
rk3568FP16, INT8FP16yolo26n-rk3568.rknn6.8 MB
rk3562FP16, INT8FP16yolo26n-rk3562.rknn6.8 MB
rk2118FP16, INT8FP16yolo26n-rk2118.rknn6.8 MB
rv1126bFP16, INT8FP16yolo26n-rv1126b.rknn7.1 MB
rv1103INT8INT8yolo26n-rv1103.rknn4.2 MB
rv1106INT8INT8yolo26n-rv1106.rknn4.2 MB
rv1103bINT8INT8yolo26n-rv1103b.rknn4.2 MB
rv1106bINT8INT8yolo26n-rv1106b.rknn4.2 MB

Bốn chip chỉ hỗ trợ INT8 được hiệu chuẩn trên coco8.yaml mặc định trong bảng này; các bản xuất tương ứng cũng ghi tail.onnx.

Lượng tử hóa#

quantize chọn độ chính xác của tệp .rknn. Kích thước bên dưới áp dụng cho bản xuất ở imgsz=640 và batch=1:

quantizePrecisionDữ liệu hiệu chuẩnCác tệp dành cho YOLO26n và rk3588Kích thước
không đặt hoặc 16FP16Khôngyolo26n-rk3588.rknn7.4 MB
8INT8Cóyolo26n-rk3588.rknn và tail.onnx4.3 MB và 0.2 MB
  • FP16: mặc định cho bảy chip hỗ trợ định dạng này. Không cần dữ liệu hiệu chuẩn.
  • INT8: quantize=8 chạy ảnh hiệu chuẩn qua model và lưu trọng số cùng activation dưới dạng số nguyên 8 bit. Quá trình xuất hiệu chuẩn trên tập chia val của data, hoặc trên tập chia được đặt bằng split, và đưa ra cảnh báo nếu có dưới 300 ảnh. Dùng fraction để giới hạn số lượng ảnh.
  • Độ chính xác hỗn hợp: trên bảy chip hỗ trợ FP16, khi xuất INT8, RKNN Toolkit cho phép giữ các layer ở FP16 nếu lượng tử hóa làm thay đổi đầu ra quá nhiều (auto_hybrid). Bốn chip chỉ hỗ trợ INT8 bỏ qua bước này.
  • Head detection: với model detect, segment, pose và OBB, tệp .rknn INT8 kết thúc ở các lớp tích chập đầu ra của head. Các phép toán giải mã những đầu ra này thành box được lưu trong tail.onnx và chạy ở dạng dấu phẩy động trên CPU của thiết bị, vì INT8 theo từng tensor không thể biểu diễn các giá trị trong phạm vi pixel dùng để giải mã box.
  • Model depth: các bản xuất depth INT8 được hiệu chuẩn trên những ảnh của tập dữ liệu depth có bản đồ độ sâu tương ứng. Hãy chọn ảnh hiệu chuẩn bao quát phạm vi độ sâu gần và xa của cảnh triển khai. Với depth8.yaml mặc định, có 4 ảnh validation, model YOLO26n-depth INT8 trong trình mô phỏng rknn-toolkit2 trả về độ sâu tối đa 3.9 cho ảnh đường phố, trong khi model FP16 trả về tối đa 13.9.
  • Trạng thái trên thiết bị: các bản xuất INT8 cho mọi tác vụ đã được chạy trong trình mô phỏng rknn-toolkit2 và so sánh với model ONNX trên một ảnh. Độ chính xác chưa được đo trên tập dữ liệu hoặc phần cứng Rockchip, vì vậy hãy validation model INT8 trên thiết bị và dữ liệu của riêng bạn trước khi triển khai.
Ví dụ
from ultralytics import YOLO

model = YOLO("yolo26n.pt")

# Hiệu chuẩn trên 10% số ảnh validation COCO (500 ảnh); thay coco.yaml bằng dataset của riêng bạn
model.export(format="rknn", name="rk3588", quantize=8, data="coco.yaml", fraction=0.1)

Định dạng đầu ra#

Quá trình xuất ghi một thư mục:

FileNội dung
yolo26n-rk3588.rknnModel, với chip được đặt bằng name trong tên tệp
tail.onnxChỉ dành cho model detect, segment, pose và OBB INT8: các phép toán giải mã đầu ra của head thành dự đoán thô để chạy trên CPU
metadata.yamlTên lớp, tác vụ, kích thước ảnh, kích thước batch, stride và các tham số xuất mà Ultralytics đọc khi tải model

Tệp yolo26n.onnx trung gian nằm cạnh thư mục. Model .rknn nhận một đầu vào có shape (batch, height, width, 3): RGB, thứ tự kênh cuối (NHWC), uint8 với giá trị từ 0 đến 255. Phép chia cho 255 đã nằm trong model, vì vậy không cần tự chuẩn hóa ảnh. Điều này khác với bản xuất ONNX, vốn nhận ảnh theo thứ tự kênh trước float32 được chuẩn hóa về 0-1.

Đầu ra tùy thuộc vào tác vụ và độ chính xác. Các shape bên dưới áp dụng cho checkpoint YOLO26n chính thức ở kích thước xuất mặc định, với checkpoint Cityscapes yolo26n-sem.pt dành cho segmentation ngữ nghĩa:

Tác vụimgsz mặc địnhĐầu ra FP16 và đầu ra tail.onnx cho INT8Đầu ra .rknn INT8
Detect640(1, 84, 8400)6 tensor của head, được giải mã bằng tail.onnx
Segment640(1, 116, 8400) và (1, 32, 160, 160)9 tensor của head và (1, 32, 160, 160), được giải mã bằng tail.onnx
Ngữ nghĩa1024(1, 19, 1024, 1024), điểm số cho mỗi lớp và pixelGiống FP16
Độ sâu768(1, 1, 768, 768), bản đồ độ sâuGiống FP16
Phân loại224(1, 1000), xác suất lớpGiống FP16
Tư thế640(1, 56, 8400)9 tensor của head, được giải mã bằng tail.onnx
OBB1024(1, 20, 21504)9 tensor của head, được giải mã bằng tail.onnx
  • Dự đoán thô: model FP16 và tail.onnx đối với model INT8 trả về cùng các dự đoán thô như bản xuất ONNX mặc định: với mỗi anchor, lần lượt là tâm box x, tâm y, chiều rộng và chiều cao tính bằng pixel đầu vào, tiếp theo là điểm số lớp rồi đến các giá trị của tác vụ (32 hệ số mask, 17 giá trị keypoint x 3 hoặc góc OBB tính bằng radian). Tự áp dụng NMS. Xem định dạng đầu ra ONNX để biết bố cục đầu ra của từng tác vụ.
  • Tensor head INT8: model detection INT8 trả về hai tensor cho mỗi một trong ba scale detection, một tensor chứa giá trị box và một tensor chứa điểm số lớp; model segmentation, pose và OBB trả về thêm một tensor mỗi scale chứa các giá trị bổ sung tương ứng. Đưa các tensor này vào tail.onnx theo thứ tự model trả về; model segmentation cũng chuyển nguyên trạng các prototype mask qua tail.onnx.
  • Segmentation ngữ nghĩa: đầu ra chứa điểm số cho mỗi lớp và pixel, không phải bản đồ lớp như trong bản xuất ONNX; vì vậy, hãy lấy argmax trên trục lớp bằng code của bạn.
  • NMS: không có đầu ra không cần NMS hoặc có NMS tích hợp; xem Giới hạn và khắc phục sự cố.

YOLO("yolo26n_rknn_model") đọc bố cục từ metadata.yaml, chạy tail.onnx và áp dụng NMS, vì vậy bạn chỉ cần các chi tiết này khi chạy model bằng code của riêng mình. Các key của metadata.yaml gồm names, task, imgsz, stride, batch, end2end, args và, với model pose, kpt_shape.

Chạy bằng RKNN Toolkit Lite2#

Để chạy model trên thiết bị mà không dùng gói Ultralytics, hãy tải model bằng gói rknn-toolkit-lite2 và, đối với model detect, segment, pose hoặc OBB INT8, chuyển đầu ra của model sang tail.onnx bằng ONNX Runtime:

# # Xuất trước: yolo export model=yolo26n.pt format=rknn name=rk3588 quantize=8 data=coco8.yaml
import numpy as np
import onnxruntime as ort
from rknnlite.api import RKNNLite

rknn = RKNNLite()
assert rknn.load_rknn("yolo26n_rknn_model/yolo26n-rk3588.rknn") == 0
assert rknn.init_runtime() == 0

image = np.zeros((1, 640, 640, 3), dtype=np.uint8)  # # ảnh đã letterbox: RGB, NHWC, 0-255
outputs = rknn.inference(inputs=[image])  # # sáu tensor head cho model detection INT8

tail = ort.InferenceSession("yolo26n_rknn_model/tail.onnx", providers=["CPUExecutionProvider"])
feed = {t.name: x.astype(np.float32) for t, x in zip(tail.get_inputs(), outputs)}
predictions = tail.run(None, feed)[0]  # # shape (1, 84, 8400), dự đoán thô cần NMS
assert predictions.shape == (1, 84, 8400), "export a detection model at imgsz=640 with quantize=8"

tail.onnx có batch size bằng 1 bất kể batch khi xuất, vì vậy hãy chạy một lần cho mỗi ảnh nếu model được xuất với batch lớn hơn. Model FP16 không có tail.onnx, còn outputs[0] đã chứa các dự đoán thô.

Triển khai#

Trên thiết bị Rockchip, cài gói bằng pip install ultralytics rồi sao chép thư mục yolo26n_rknn_model/ sang thiết bị; các phiên bản protobuf và numpy trong Quickstart chỉ cần cho quá trình xuất. Sau đó, YOLO("yolo26n_rknn_model") chạy model trên NPU bằng gói Python rknn-toolkit-lite2; Ultralytics sẽ cài gói này khi sử dụng lần đầu, cùng với onnxruntime nếu thư mục có chứa tail.onnx. Thiết bị cần Python 3.12 trở xuống, là phiên bản mới nhất mà rknn-toolkit-lite2 có bản dựng.

  • Cần có thiết bị Rockchip: Ultralytics chỉ tải model RKNN trên các hệ thống Linux ARM 64-bit có chuỗi compatible trong device tree kết thúc bằng một trong các tên chip được hỗ trợ. Ở mọi môi trường khác, thao tác tải model sẽ thất bại; xem Giới hạn và khắc phục sự cố. rknn-toolkit-lite2 cũng chỉ có bản dựng cho Linux ARM 64-bit, vì vậy trên mục tiêu không đáp ứng các điều kiện này, hãy chạy tệp .rknn bằng C API của Rockchip rồi chạy tail.onnx hoặc tự triển khai cách giải mã tương tự trong code của bạn.
  • Chip tương thích: xuất model bằng name tương ứng với chip trên board của bạn.
  • Shape đầu vào cố định: model luôn chạy ở imgsz và batch được đặt khi xuất; Ultralytics đọc các giá trị này từ metadata.yaml. imgsz được truyền cho predict hoặc val sẽ bị bỏ qua. Batch lớn hơn được chia thành các phần theo batch size lúc xuất, còn batch nhỏ hơn được thêm padding, vì vậy có thể xử lý số lượng ảnh bất kỳ.
  • device: không có thiết bị để chọn. Model .rknn chạy qua runtime RKNN, còn tail.onnx chạy bằng ONNX Runtime trên CPU.

Một phiên bản trước đó của quy trình này đã được thử nghiệm trên Radxa Rock 5B (RK3588) và Radxa Zero 3W (RK3566). Bản xuất INT8 hiện tại vẫn chưa được chạy trên phần cứng.

Hướng dẫn triển khai#

Giới hạn và khắc phục sự cố#

  • Máy dùng để xuất: xuất trên máy Linux x86-64. Trên macOS, quá trình xuất không thể cài đặt rknn-toolkit2 và thất bại với No module named 'rknn'; gói này không có bản dựng cho macOS hoặc Windows. Việc xuất trên Linux ARM64, bao gồm các board Rockchip, chưa được kiểm thử và không được hỗ trợ: Ultralytics chỉ kiểm thử bản xuất RKNN trên Linux x86-64.

  • Phiên bản Python: rknn-toolkit2 2.3.2 có bản dựng cho Python 3.12 trở xuống. Nếu dùng Python mới hơn, hãy tạo môi trường bằng Python 3.12.

  • Lần xuất đầu tiên trong môi trường mới: trong môi trường chưa có các phiên bản protobuf và numpy theo Quickstart, lần xuất đầu tiên sẽ thay thế các gói này trong quá trình chạy rồi thất bại. Khi thay thế protobuf 7, gói mà pip cài cùng với onnx, lỗi sẽ là AttributeError: 'google._upb._message.FieldDescriptor' object has no attribute 'label'; khi chỉ thay thế numpy, lỗi sẽ là TypeError: only 0-dimensional arrays can be converted to Python scalars. Chạy lại quá trình xuất trong một tiến trình mới; nếu dùng notebook, hãy khởi động lại kernel. Hoặc cài "protobuf<7" "numpy<2.4" trước lần xuất đầu tiên như trong Quickstart.

  • Model RKNN không chạy trên PC: thao tác predict hoặc validate với YOLO("yolo26n_rknn_model") sẽ thất bại với RKNN inference is only supported on Rockchip devices. trên PC và trên board có chuỗi /proc/device-tree/compatible không kết thúc bằng một trong các tên chip được hỗ trợ. In chuỗi này bằng cat /proc/device-tree/compatible.

  • FP32: quantize=32 thất bại với quantize=32 (FP32) is not supported; format='rknn' supports quantize=16 (FP16), 8 (INT8).

  • Chip chỉ hỗ trợ INT8: với rv1103, rv1106, rv1103b và rv1106b, khi xuất mà không có quantize, hệ thống ghi log Rockchip target 'rv1106' requires INT8 quantization, enabling it. và tạo model INT8; quantize=16 sẽ thất bại với Rockchip target 'rv1106' only supports INT8, but got quantize=16.

  • Thiếu hoặc sai name: nếu không có name, quá trình xuất ghi log Rockchip RKNN export requires a missing 'name' arg for processor type. Using default name='rk3588'.. Giá trị không hợp lệ sẽ gây lỗi Invalid processor name 'rk9999' for Rockchip RKNN export., sau đó liệt kê các tên hợp lệ.

  • Head không cần NMS: model RKNN luôn trả về dự đoán thô cần NMS. Với nms=False, quá trình xuất model YOLO26 hoặc YOLOv10 ghi log This export format does not support end2end models, disabling the end2end branch. và dùng head one-to-many; với các model detect, segment, pose và OBB khác, chẳng hạn YOLO11, quá trình này ghi log This model has no one-to-one head; using one-to-many outputs.. Model classification, segmentation ngữ nghĩa và depth bỏ qua nms=False.

  • NMS tích hợp: nms=True ghi log format=rknn does not support embedded NMS; exporting native outputs for external NMS. và ghi đầu ra thô.

  • Checkpoint được huấn luyện bằng quantize=8: checkpoint được fine-tune bằng huấn luyện nhận biết lượng tử hóa sẽ thất bại với format='rknn' cannot export a QAT model: its Q/DQ ranges are only read by the 'onnx' and 'engine' backends. Thay vào đó, hãy xuất checkpoint ban đầu trước khi fine-tune bằng quantize=8.

  • RT-DETR: với rknn-toolkit2 2.3.2, quá trình xuất model RT-DETR thất bại bên trong bộ công cụ ở cả FP16 và INT8, tại imgsz=640 cho rtdetr-l.pt với ValueError: operands could not be broadcast together with shapes (256,256) (8400,1).

  • Shape đầu vào cố định: dynamic=True thất bại với argument 'dynamic' is not supported for format='rknn'. Hãy xuất lại để thay đổi kích thước ảnh hoặc batch size.

  • Hiệu chuẩn khi thiếu data: bản xuất model detection quantize=8 ghi log INT8 export requires a missing 'data' arg for calibration. Using default 'data=coco8.yaml'. và hiệu chuẩn trên tập dữ liệu nhỏ đó; các tác vụ khác nêu tên tập dữ liệu mặc định tương ứng. Truyền data cùng ảnh đại diện cho dữ liệu triển khai của bạn.

  • Kích thước tập hiệu chuẩn: quá trình xuất ghi log >300 images recommended for INT8 calibration, found 4 images. khi tập chia hiệu chuẩn có dưới 300 ảnh. coco8.yaml chỉ có 4 ảnh validation, đủ để kiểm thử quá trình xuất nhưng không đủ để hiệu chuẩn model dùng trong triển khai.

  • Thư mục đầu ra: mỗi lần xuất cùng một checkpoint đều ghi vào thư mục yolo26n_rknn_model/, bất kể name, quantize, imgsz hay batch của lần xuất đó, đồng thời xóa nội dung cũ trước. Hãy đổi tên thư mục trước khi xuất cho chip hoặc độ chính xác thứ hai, và giữ _rknn_model trong tên, chẳng hạn yolo26n_rk3566_rknn_model/, vì Ultralytics nhận diện định dạng dựa vào chuỗi này.

  • ONNX opset: opset lớn hơn 19 sẽ ghi log rknn-toolkit2 requires opset<=19, setting opset=19.

  • Model INT8 từ các phiên bản trước: xuất lại các model phát hiện, phân đoạn, tư thế và OBB INT8 đã được xuất trước phiên bản ultralytics 8.4.191, bản phát hành bổ sung tail.onnx. Các model đó trả về tọa độ hộp và keypoint tương đối với kích thước đầu vào; các bản phát hành hiện tại không còn co giãn lại tọa độ, vì vậy model tải mà không báo lỗi nhưng trả về các hộp sai.

  • Không khớp phiên bản runtime: nếu nhật ký trên thiết bị cho biết phiên bản runtime RKNN không khớp với phiên bản RKNN Toolkit và quá trình suy luận thất bại, hãy thay /usr/lib/librknnrt.so bằng tệp librknnrt.so chính thức.

    Cảnh báo trong nhật ký RKNN cho biết phiên bản model toolkit không khớp với phiên bản runtime librknnrt

Đối với các lỗi khác, hãy xem hướng dẫn về các sự cố thường gặp.

Benchmark#

Các kết quả benchmark YOLO26 bên dưới do nhóm Ultralytics thực hiện trên Radxa Rock 5B dùng Rockchip RK3588, với model ở định dạng rknn để đo tốc độ và độ chính xác.

Hiệu năng
ModelĐịnh dạngPrecisionTrạng tháiKích thước (MB)mAP50-95(B)Thời gian suy luận (ms/ảnh)
YOLO26nrknnFP16✅7.20.47758.5
YOLO26nrknnINT8✅4.10.46341.2
YOLO26srknnFP16✅21.00.56993.8
YOLO26srknnINT8✅12.00.55461.9
YOLO26mrknnFP16✅43.00.608226.3
YOLO26mrknnINT8✅22.00.603122.0
YOLO26lrknnFP16✅53.00.628264.7
YOLO26lrknnINT8✅28.00.617145.3
YOLO26xrknnFP16✅113.00.664655.4
YOLO26xrknnINT8✅58.00.649287.4

Benchmark bằng ultralytics 8.4.60

Lưu ý

Việc xác thực cho các benchmark phía trên được thực hiện bằng tập dữ liệu COCO128. Thời gian suy luận không bao gồm tiền xử lý/hậu xử lý. Các hàng INT8 sẽ được cập nhật khi luồng xuất INT8 hiện tại (giải mã phía host và auto_hybrid) được xác thực trên phần cứng Rockchip.

Các kích thước trong bảng được ghi lại bằng phiên bản trước đó; kích thước ở những nơi khác trên trang này là kích thước tệp .rknn của một bản xuất hiện tại, tính bằng MB (10^6 byte). Trang model YOLO26 liệt kê độ chính xác của các checkpoint PyTorch trên toàn bộ tập xác thực COCO.

Giới thiệu về RKNN#

Rockchip thiết kế các hệ thống trên chip dựa trên ARM với NPU tích hợp, được sử dụng trong máy tính bo mạch đơn và các sản phẩm nhúng của những công ty như Radxa, ASUS, Pine64, Orange Pi, Odroid, Khadas và Banana Pi. RKNN, viết tắt của Mạng nơ-ron Rockchip, là định dạng model dành cho các NPU đó; RKNN Toolkit chuyển đổi model sang định dạng này trên PC và chạy model trên thiết bị.

Rockchip RKNN export for NPU deployment

Câu hỏi thường gặp#

  • Hãy dùng tên bộ xử lý trên bo mạch, không phải tên bo mạch: chẳng hạn rk3588 cho Radxa Rock 5B hoặc rk3566 cho Radxa Zero 3W. Trên bo mạch, cat /proc/device-tree/compatible in ra chuỗi mà Ultralytics dùng để nhận diện chip. Model được xuất cho một chip sẽ không chạy trên chip khác, vì vậy hãy xuất riêng cho từng chip. Xem Chip mục tiêu để biết các tên được chấp nhận.

  • Hãy bắt đầu với FP16, định dạng mặc định. FP16 không cần dữ liệu hiệu chuẩn và trả về các dự đoán thô mà không cần model thứ hai chạy trên CPU. Chọn INT8 (quantize=8) khi bạn cần model nhỏ hơn và nhanh hơn, hoặc khi chip chỉ hỗ trợ INT8: YOLO26n cho RK3588 có kích thước 4.3 MB ở INT8 so với 7.4 MB ở FP16; trong các kết quả benchmark, được đo bằng bản xuất trước đó, INT8 chạy YOLO26n mất 41.2 ms mỗi ảnh so với 58.5 ms ở FP16. INT8 cần dữ liệu hiệu chuẩn đại diện; với model phát hiện, phân đoạn, tư thế và OBB, INT8 chạy giải mã hộp trên CPU bằng tail.onnx. Hãy đo độ trễ và độ chính xác trên thiết bị của bạn trước khi lựa chọn.

  • Không thể dùng YOLO(), vì công cụ này chỉ tải model RKNN trên thiết bị Rockchip. Để kiểm tra chính model trên PC, hãy xác thực checkpoint PyTorch hoặc tệp yolo26n.onnx trung gian mà quá trình xuất tạo ra bên cạnh thư mục, bằng ONNX Runtime: model RKNN được chuyển đổi từ đồ thị đó. Việc này không thay thế cho xác thực trên thiết bị, đặc biệt với INT8, vì lượng tử hóa làm thay đổi đầu ra.

  • Có, bằng định dạng xuất tương ứng với từng bộ tăng tốc: model RKNN chỉ chạy trên NPU Rockchip. Xem TensorRT cho NVIDIA Jetson, Hailo, Axelera, DeepX và Coral Edge TPU; hoặc xem hướng dẫn các tùy chọn triển khai model để biết tổng quan.

Bình luận45

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. as-jacksonGitHub

    We are pleased to confirm that the following ArmSoM boards based on Rockchip RK3576 have been successfully tested with Ultralytics projects (e.g., YOLO11n):

    ArmSoM-Sige5 ArmSoM-CM5

    Validation Scope:

    Model training/inference pipeline

    1
  2. yizi72GitHub

    I tried to convert the yolo11n.pt into a rknn model through codes below: from ultralytics import YOLO model = YOLO("yolo11n.pt") model.export(format="rknn", name="rk3588") and everything went correct. A rknn model named yolo11n-rk3588.rknn was build and used to infer a very traditional yolo demo image "bus"(a blue bus with several people in front of it), but no detection result was obtained.

    I tried to convert the yolol11n.pt into onnx model through above codes firstly, and then used a convert.py offered by rknn_model_zoo/examples/yolo11/python,

    import sys from rknn.api import RKNN

    DATASET_PATH = '../../../datasets/COCO/coco_subset_20.txt' DEFAULT_RKNN_PATH = '/home/yizi/model/yolo11/yolodet.rknn' DEFAULT_QUANT = False

    def parse_arg(): if len(sys.argv) < 3: print("Usage: python3 {} onnx_model_path [platform] [dtype(optional)] [output_rknn_path(optional)]".format(sys.argv[0])) print(" platform choose from [rk3562,rk3566,rk3568,rk3588,rk3576,rk1808,rv1109,rv1126]") print(" dtype choose from [i8, fp] for [rk3562,rk3566,rk3568,rk3588,rk3576]") print(" dtype choose from [u8, fp] for [rk1808,rv1109,rv1126]") exit(1)

    model_path = sys.argv[1]
    platform = sys.argv[2]
    
    do_quant = DEFAULT_QUANT
    if len(sys.argv) > 3:
        model_type = sys.argv[3]
        if model_type not in ['i8', 'u8', 'fp']:
            print("ERROR: Invalid model type: {}".format(model_type))
            exit(1)
        elif model_type in ['i8', 'u8']:
            do_quant = True
        else:
            do_quant = False
    
    if len(sys.argv) > 4:
        output_path = sys.argv[4]
    else:
        output_path = DEFAULT_RKNN_PATH
    
    return model_path, platform, do_quant, output_path

    if name == 'main': model_path, platform, do_quant, output_path = parse_arg()

    # Create RKNN object
    rknn = RKNN(verbose=False)
    
    # Pre-process config
    print('--> Config model')
    rknn.config(mean_values=[[0, 0, 0]], std_values=[[255, 255, 255]], target_platform=platform)
    print('done')
    
    # Load model
    print('--> Loading model')
    ret = rknn.load_onnx(model=model_path)
    if ret != 0:
        print('Load model failed!')
        exit(ret)
    print('done')
    
    # Build model
    print('--> Building model')
    ret = rknn.build(do_quantization=do_quant, dataset=DATASET_PATH)
    if ret != 0:
        print('Build model failed!')
        exit(ret)
    print('done')
    
    # Export rknn model
    print('--> Export rknn model')
    ret = rknn.export_rknn(output_path)
    if ret != 0:
        print('Export rknn model failed!')
        exit(ret)
    print('done')
    
    # Release
    rknn.release()

    Still everything went correct. A rknn model was created and applied to "bus.jpg", and there was no detection at all. I wonder what's wrong in the whole process?

    1
    1. Glenn JocherUltralytics

      @yizi72 thanks for the detailed report. For RKNN inference issues with YOLO11, please ensure:

      1. You're using matching RKNN Toolkit and runtime versions (update both if needed)
      2. Input images are 640x640 with pixel values normalized 0-255
      3. You load models via YOLO('./yolo11n_rknn_model') as shown in our RKNN deployment docs

      If issues persist, please share your full environment details and validation results from both export methods.

    2. yizi72GitHub

      1、I used rknn-toolkit2-2.3.0 which is the latest version ,bu I still did "pip install rknn-toolkit2 --upgrade" again. 2、The input image is 640*640, uchar, 0-255. 3. I used the following setting to transfer yolo11n.pt to onnx, from ultralytics import YOLO

      加载一个模型,路径为 YOLO 模型的 .pt 文件

      model = YOLO("yolo11n.pt")

      导出模型,设置多种参数

      model.export( format="onnx", imgsz=(640, 640),
      keras=False,
      optimize=True,
      half=False,
      int8=False,
      dynamic=False,
      simplify=True,
      opset=12,
      #workspace=4.0,
      nms=False,
      batch=1
      ) and applied the following codes to verify yolo11n.onnx model:

      from ultralytics import YOLO from PIL import Image

      Load a model

      model = YOLO("/home/yizi/models/yolo11/yolo11n.onnx") # load an official model

      Predict with the model

      results = model("bus.jpg") # predict on an image #results = rknn_model("bus.jpg")

      Access the results

      for result in results: xywh = result.boxes.xywh # center-x, center-y, width, height xywhn = result.boxes.xywhn # normalized xyxy = result.boxes.xyxy # top-left-x, top-left-y, bottom-right-x, bottom-right-y xyxyn = result.boxes.xyxyn # normalized names = [result.names[cls.item()] for cls in result.boxes.cls.int()] # class name of each box confs = result.boxes.conf # confidence score of each box

      The results are good. All objects in bus.jpg were detected. Then I run the following code to transfer onnx to rknn:

      from rknn.api import RKNN import cv2 import numpy as np

      if name == 'main': rknn = RKNN(verbose=True,verbose_file="log.txt") rknn.config( mean_values=[[0, 0, 0]], std_values=[[255, 255, 255]], target_platform="rk3588", optimization_level=3 )

      rknn.load_onnx(
          model="/home/yizi/models/yolo11/yolo11n.onnx",
          input_size_list=[[1,3,640,640]], 

      )

      rknn.build(
          do_quantization=False 
      )
      
      rknn.export_rknn(
          export_path="/home/yizi/models/yolo11/yolo11n.rknn" 
      )
      
      rknn.release()

      The transferring process went smooth, two problems appeared.

      Firstly,when this rknn model was pushed into a rk3588 tablet, and run with a binary executable file generated by cross-compilation, no result was detected.

      Secondly, I tried to run the following codes:

      from ultralytics import YOLO from PIL import Image

      rknn_model = YOLO("/home/yizi/models/yolo11/yolo11n.rknn", task=detect)

      results = model("bus.jpg")

      An error message, "model='/home/yizi/models/yolo11/yolo11n.rknn' is not a supported model format. Ultralytics supports: ('PyTorch', 'TorchScript', 'ONNX', 'OpenVINO', 'TensorRT', 'CoreML', 'TensorFlow SavedModel', 'TensorFlow GraphDef', 'TensorFlow Lite', 'TensorFlow Edge TPU', 'TensorFlow.js', 'PaddlePaddle', 'MNN', 'NCNN', 'IMX', 'RKNN') See https://docs.ultralytics.com/modes/predict for help. " appeared.

      Last question, how many outputs does yolo11 yield? one or six?

    3. Glenn JocherUltralytics

      @yizi72 thank you for the detailed report. For RKNN deployment issues:

      1. When using Ultralytics RKNN export, load models via the exported directory (not .rknn file), as shown in our RKNN deployment docs:
      model = YOLO('./yolo11n_rknn_model')  # directory path
      1. Ensure your RK3588 runtime uses matching librknnrt.so versions with your RKNN Toolkit 2.3.0 installation

      2. YOLO11 detection models output 3 tensors by default (different from older YOLO versions). For conversion issues, we recommend using our native model.export(format='rknn') rather than manual ONNX conversion.

      Let me know if you still face issues after verifying these points.

    4. yizi72GitHub

      Thanks for replies. I did verify all points you've mentioned above. When running model("bus.jpg"), error messages show:

      File "/home/yizi/anaconda3/envs/rknn/lib/python3.9/site-packages/ultralytics/engine/model.py", line 182, in call return self.predict(source, stream, **kwargs) File "/home/yizi/anaconda3/envs/rknn/lib/python3.9/site-packages/ultralytics/engine/model.py", line 543, in predict self.predictor.setup_model(model=self.model, verbose=is_cli) File "/home/yizi/anaconda3/envs/rknn/lib/python3.9/site-packages/ultralytics/engine/predictor.py", line 378, in setup_model self.model = AutoBackend( File "/home/yizi/anaconda3/envs/rknn/lib/python3.9/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context return func(*args, **kwargs) File "/home/yizi/anaconda3/envs/rknn/lib/python3.9/site-packages/ultralytics/nn/autobackend.py", line 495, in init raise OSError("RKNN inference is only supported on Rockchip devices.") OSError: RKNN inference is only supported on Rockchip devices.

      It's very strange because I did connect a RK3588 tablet with my virtual machine.

      I still have a quesiton on yolo11n output: yolo11n.pt has one output with shape (1, 84, 8400), and yolo11n-rk3588.rknn has one output with shape (1,84, 8400, 0). Are they correct? If so, can I use the similar codes to analyze rknn output, such as :

      for result in results: xywh = result.boxes.xywh # center-x, center-y, width, height xywhn = result.boxes.xywhn # normalized xyxy = result.boxes.xyxy # top-left-x, top-left-y, bottom-right-x, bottom-right-y xyxyn = result.boxes.xyxyn # normalized names = [result.names[cls.item()] for cls in result.boxes.cls.int()] # class name of each box confs = result.boxes.conf

    5. Glenn JocherUltralytics

      @yizi72 thanks for the details. For the RKNN inference error: ensure your Python script is running directly on the RK3588 hardware (not through a VM) as RKNN models require native Rockchip NPU access. Regarding outputs, YOLO11 detection models produce 3 output tensors by default (see our RKNN deployment docs), but your code should work if using the exported RKNN directory with the included postprocessing. Let me know if you still face issues after verifying native hardware execution.

  3. Yufeng Wu

    Hello, Ultralytics team. I wonder if it's possible to port yolo26n-pose to rknn? I'm not sure if it's difficult to work out on my own? Is there any model architecture problems that prevent porting the pose models to rknn?

  4. montemadjoGitHub

    It appears it does not support rv1106 platform yet

    When I try to export the model using this command

    model.export(format="rknn", name="rv1106", imgsz=320)

    It gives the following error

    E build: Current target_platform(rv1106) not support do_quantization = False!
    E export_rknn: RKNN model does not exist, please load & build model first!

    🤔

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      rv1106 is an INT8-only target, so it needs a quantized RKNN build. Older Ultralytics releases always built with do_quantization=False, which fails with the message you saw. Current releases support it: upgrade with pip install -U ultralytics and export with quantize=8 plus calibration data:

      model.export(format="rknn", name="rv1106", imgsz=320, quantize=8, data="coco8.yaml")

      See the Rockchip RKNN export guide. If it still fails, share your !yolo checks output and rknn-toolkit2 version here and we can sanity-check the environment.

      1
    2. montemadjoGitHub(đã chỉnh sửa)

      Here's the quick workaround for those who want to work with yolo26 on RV1106 chip (like Luckfox pico etc). I ran into a couple of issues there, including quantization erasing my confidence results.

      Long story short - first you need to monkey-patch head.Detect.forward function in order to get two tensors - one for bboxes and one for scores. That way you escape all the heavy non-supported tensor functions. Then you export your yolo26 model to onnx format and finally to rknn like this

      import torch
      from ultralytics.nn.modules import head
      
      # 1. First we monkey-patch the forward function
      def patched_forward(self, x):
          if self.end2end:
              h = self.one2one
          else:
              h = self.one2many
      
          box_head = h["box_head"]
          cls_head = h["cls_head"]
      
          if box_head is None or cls_head is None:
              raise RuntimeError("Head moduls are None")
      
          bs = x[0].shape[0]
          boxes = torch.cat([box_head[i](x[i]).view(bs, 4 * self.reg_max, -1) for i in range(self.nl)], dim=-1)
          scores = torch.cat([cls_head[i](x[i]).view(bs, self.nc, -1) for i in range(self.nl)], dim=-1)
      
          preds = {"boxes": boxes, "scores": scores, "feats": x}
          y = self._inference(preds)
      
          # We are splitting into 2 tensors - both gets its own scale/zp at INT8 quantization
          bboxes = y[:, :4, :]   # [1, 4, 2100] — range 0-640
          scores = y[:, 4:, :]   # [1, 1, 2100] — range 0-1 (already sigmoid-ed)
          score_max_idx = scores[0, 0, :].argmax()
          return bboxes, scores
      
      head.Detect.forward = patched_forward
      
      # 2. Then we export to onnx model (we got best.pt model from ultralytics platform)
      from ultralytics import YOLO
      model = YOLO("best.pt")
      model.export(format="onnx", dynamic=False, opset=12, imgsz=320)
      
      # 3. Then we export to RKNN format
      from rknn.api import RKNN
      
      rknn = RKNN()
      
      # 3.1. Konfiguracija specifična za RV1106
      rknn.config(
          mean_values=[[0, 0, 0]], 
          std_values=[[255, 255, 255]], 
          target_platform='rv1106',
          quantized_algorithm='normal', # Ili 'mmse' za bolju preciznost
          quantized_dtype='asymmetric_quantized-8'
      )
      
      # 3.2. Load the ONNX model
      print("Loading ONNX model...")
      rknn.load_onnx(model='best.onnx')
      
      # 3.3. Build modela sa INT8 kvantizacijom
      # calib.txt should contain paths to calibration images
      print("Building RKNN model with quantization...")
      rknn.build(do_quantization=True, dataset='./calib.txt')
      
      # 3.4. Exporting final .rknn file
      print("Exporting RKNN model...")
      rknn.export_rknn('./yolo26_rv1106_model_optimized.rknn')
      
      rknn.release()

      After this you need to postprocess those two outputs like this

      yolo26_postprocess.h

      /**
       * YOLO26 Post-processing header for Fish Counter
       *
       * Supports YOLO26 2-output format: boxes [1, 4, N] + scores [1, nc, N]
       *
       * Based on the working rknn_minimal_test example.
       */
      
      #ifndef _YOLO26_POSTPROCESS_H_
      #define _YOLO26_POSTPROCESS_H_
      
      #include <stdint.h>
      #include <vector>
      #include "rknn_api.h"
      #include "rknn_detector.h"
      
      // YOLO26 model configuration defaults
      #define YOLO26_CONF_THRESHOLD 0.25f
      #define YOLO26_NMS_THRESHOLD 0.45f
      
      // Detection result (same structure as postprocess.h for compatibility)
      typedef struct
      {
          float x1, y1, x2, y2; // Bounding box (in model coordinates)
          float confidence;
          int class_id;
      } yolo26_detection_t;
      
      // YOLO26 context for format detection and caching
      typedef struct
      {
          int num_predictions;
          int num_classes;
          bool boxes_transposed; // true = [1, 4, N], false = [1, N, 4]
      } yolo26_context_t;
      
      /**
       * Initialize YOLO26 post-processing
       * Detects the output format from model attributes
       *
       * @param app_ctx The RKNN app context with model info
       * @param yolo26_ctx Output: YOLO26 context for format info
       * @return 0 on success, -1 on error
       */
      int yolo26_init_postprocess(rknn_app_context_t *app_ctx, yolo26_context_t *yolo26_ctx);
      
      /**
       * Deinitialize YOLO26 post-processing
       */
      void yolo26_deinit_postprocess();
      
      /**
       * YOLO26 post_process: processes model outputs and returns detections
       * Uses 2-output format: boxes [1, 4, N] + scores [1, nc, N]
       *
       * @param app_ctx The RKNN app context
       * @param yolo26_ctx YOLO26 context from init
       * @param outputs Pointer to output tensor memory array
       * @param letter_box Letterbox transform info for coordinate mapping
       * @param conf_threshold Confidence threshold
       * @param nms_threshold NMS threshold
       * @param od_results Output: detection results (compatible with existing code)
       * @return 0 on success, -1 on error
       */
      int yolo26_post_process(rknn_app_context_t *app_ctx, yolo26_context_t *yolo26_ctx,
                              void *outputs, letterbox_t *letter_box,
                              float conf_threshold, float nms_threshold,
                              object_detect_result_list *od_results);
      
      #endif // _YOLO26_POSTPROCESS_H_

      yolo26_postprocess.cc

      /**
       * YOLO26 Post-processing for Fish Counter on RV1106
       *
       * Supports YOLO26 2-output format: boxes [1, 4, N] + scores [1, nc, N]
       *
       * Based on the working rknn_minimal_test example.
       */
      
      #include "yolo26_postprocess.h"
      
      #include <math.h>
      #include <stdint.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <algorithm>
      #include <vector>
      
      // Clamp value to range
      inline static int clamp(float val, int min, int max)
      {
          return val > min ? (val < max ? val : max) : min;
      }
      
      // Dequantize INT8 to float
      static inline float dequantize(int8_t qnt, int32_t zp, float scale)
      {
          return ((float)qnt - (float)zp) * scale;
      }
      
      // Sigmoid function
      static inline float sigmoid(float x)
      {
          return 1.0f / (1.0f + expf(-x));
      }
      
      // Calculate IoU between two boxes
      static float calculate_iou(float x1_a, float y1_a, float x2_a, float y2_a,
                                 float x1_b, float y1_b, float x2_b, float y2_b)
      {
          float x1 = std::max(x1_a, x1_b);
          float y1 = std::max(y1_a, y1_b);
          float x2 = std::min(x2_a, x2_b);
          float y2 = std::min(y2_a, y2_b);
      
          float inter_w = std::max(0.0f, x2 - x1);
          float inter_h = std::max(0.0f, y2 - y1);
          float inter_area = inter_w * inter_h;
      
          float area_a = (x2_a - x1_a) * (y2_a - y1_a);
          float area_b = (x2_b - x1_b) * (y2_b - y1_b);
          float union_area = area_a + area_b - inter_area;
      
          return union_area > 0 ? inter_area / union_area : 0;
      }
      
      // Non-Maximum Suppression for YOLO26 detections
      static std::vector<yolo26_detection_t> yolo26_nms(std::vector<yolo26_detection_t> &detections, float nms_threshold)
      {
          // Sort by confidence (descending)
          std::sort(detections.begin(), detections.end(),
                    [](const yolo26_detection_t &a, const yolo26_detection_t &b)
                    { return a.confidence > b.confidence; });
      
          std::vector<yolo26_detection_t> result;
          std::vector<bool> suppressed(detections.size(), false);
      
          for (size_t i = 0; i < detections.size(); i++)
          {
              if (suppressed[i])
                  continue;
      
              result.push_back(detections[i]);
      
              for (size_t j = i + 1; j < detections.size(); j++)
              {
                  if (suppressed[j])
                      continue;
      
                  // Only suppress same class
                  if (detections[i].class_id != detections[j].class_id)
                      continue;
      
                  float iou = calculate_iou(
                      detections[i].x1, detections[i].y1, detections[i].x2, detections[i].y2,
                      detections[j].x1, detections[j].y1, detections[j].x2, detections[j].y2);
      
                  if (iou > nms_threshold)
                  {
                      suppressed[j] = true;
                  }
              }
          }
      
          return result;
      }
      
      // Parse YOLO26 2-output format: boxes [1, 4, N] + scores [1, nc, N]
      static std::vector<yolo26_detection_t> parse_yolo26_2output(
          rknn_tensor_mem **output_mems,
          rknn_tensor_attr *output_attrs,
          int model_width, int model_height,
          float conf_threshold, int num_classes,
          bool boxes_transposed)
      {
          std::vector<yolo26_detection_t> detections;
      
          int8_t *boxes_data = (int8_t *)output_mems[0]->virt_addr;
          int32_t boxes_zp = output_attrs[0].zp;
          float boxes_scale = output_attrs[0].scale;
      
          int8_t *scores_data = (int8_t *)output_mems[1]->virt_addr;
          int32_t scores_zp = output_attrs[1].zp;
          float scores_scale = output_attrs[1].scale;
      
          // Determine number of anchors
          int num_anchors;
          if (boxes_transposed)
          {
              num_anchors = output_attrs[0].dims[2];
          }
          else
          {
              num_anchors = output_attrs[0].dims[1];
          }
      
          // Check if scores are already sigmoid or logits
          float scores_min = 9999, scores_max = -9999;
          for (int i = 0; i < (int)output_attrs[1].n_elems; i++)
          {
              float val = dequantize(scores_data[i], scores_zp, scores_scale);
              if (val < scores_min)
                  scores_min = val;
              if (val > scores_max)
                  scores_max = val;
          }
          bool scores_are_sigmoid = (scores_min >= -0.1f && scores_max <= 1.1f);
      
          for (int i = 0; i < num_anchors; i++)
          {
              // Get box coordinates
              float x1, y1, x2, y2;
              if (boxes_transposed)
              {
                  // [1, 4, N] - channel first
                  x1 = dequantize(boxes_data[0 * num_anchors + i], boxes_zp, boxes_scale);
                  y1 = dequantize(boxes_data[1 * num_anchors + i], boxes_zp, boxes_scale);
                  x2 = dequantize(boxes_data[2 * num_anchors + i], boxes_zp, boxes_scale);
                  y2 = dequantize(boxes_data[3 * num_anchors + i], boxes_zp, boxes_scale);
              }
              else
              {
                  // [1, N, 4] - anchor first
                  x1 = dequantize(boxes_data[i * 4 + 0], boxes_zp, boxes_scale);
                  y1 = dequantize(boxes_data[i * 4 + 1], boxes_zp, boxes_scale);
                  x2 = dequantize(boxes_data[i * 4 + 2], boxes_zp, boxes_scale);
                  y2 = dequantize(boxes_data[i * 4 + 3], boxes_zp, boxes_scale);
              }
      
              // Check if format is xywh instead of xyxy
              if (x2 < x1 || y2 < y1)
              {
                  // Assume xywh format: convert to xyxy
                  float cx = x1, cy = y1, w = x2, h = y2;
                  x1 = cx - w / 2.0f;
                  y1 = cy - h / 2.0f;
                  x2 = cx + w / 2.0f;
                  y2 = cy + h / 2.0f;
              }
      
              // Find max class score
              float max_score = -9999;
              int max_class = 0;
              for (int c = 0; c < num_classes; c++)
              {
                  float score;
                  if (boxes_transposed)
                  {
                      // [1, nc, N]
                      score = dequantize(scores_data[c * num_anchors + i], scores_zp, scores_scale);
                  }
                  else
                  {
                      // [1, N, nc]
                      score = dequantize(scores_data[i * num_classes + c], scores_zp, scores_scale);
                  }
      
                  if (!scores_are_sigmoid)
                  {
                      score = sigmoid(score);
                  }
      
                  if (score > max_score)
                  {
                      max_score = score;
                      max_class = c;
                  }
              }
      
              if (max_score < conf_threshold)
                  continue;
      
              // Clamp to model bounds
              x1 = std::max(0.0f, std::min(x1, (float)model_width));
              y1 = std::max(0.0f, std::min(y1, (float)model_height));
              x2 = std::max(0.0f, std::min(x2, (float)model_width));
              y2 = std::max(0.0f, std::min(y2, (float)model_height));
      
              // Skip invalid boxes
              if (x2 <= x1 || y2 <= y1)
                  continue;
      
              yolo26_detection_t det;
              det.x1 = x1;
              det.y1 = y1;
              det.x2 = x2;
              det.y2 = y2;
              det.confidence = max_score;
              det.class_id = max_class;
      
              detections.push_back(det);
          }
      
          return detections;
      }
      
      int yolo26_init_postprocess(rknn_app_context_t *app_ctx, yolo26_context_t *yolo26_ctx)
      {
          if (!app_ctx || !yolo26_ctx)
          {
              printf("[YOLO26] ERROR: Invalid parameters\n");
              return -1;
          }
      
          memset(yolo26_ctx, 0, sizeof(yolo26_context_t));
      
          int n_output = app_ctx->io_num.n_output;
      
          printf("[YOLO26] Initializing 2-output format (%d outputs)...\n", n_output);
      
          // Print output tensor info
          for (int i = 0; i < n_output; i++)
          {
              printf("  Output %d: dims=[%d,%d,%d,%d], size=%d\n", i,
                     app_ctx->output_attrs[i].dims[0],
                     app_ctx->output_attrs[i].dims[1],
                     app_ctx->output_attrs[i].dims[2],
                     app_ctx->output_attrs[i].dims[3],
                     app_ctx->output_attrs[i].size);
          }
      
          if (n_output != 2)
          {
              printf("[YOLO26] ERROR: Expected 2 outputs (boxes + scores), got %d\n", n_output);
              return -1;
          }
      
          // Parse 2-output format: boxes + scores
          int boxes_dim1 = app_ctx->output_attrs[0].dims[1];
          int boxes_dim2 = app_ctx->output_attrs[0].dims[2];
          int scores_dim1 = app_ctx->output_attrs[1].dims[1];
          int scores_dim2 = app_ctx->output_attrs[1].dims[2];
      
          if (boxes_dim1 == 4)
          {
              // [1, 4, N] boxes format
              yolo26_ctx->num_predictions = boxes_dim2;
              yolo26_ctx->boxes_transposed = true;
              yolo26_ctx->num_classes = scores_dim1;
              printf("[YOLO26] Format: boxes [1,4,%d], scores [1,%d,%d]\n",
                     boxes_dim2, scores_dim1, scores_dim2);
          }
          else if (boxes_dim2 == 4)
          {
              // [1, N, 4] boxes format
              yolo26_ctx->num_predictions = boxes_dim1;
              yolo26_ctx->boxes_transposed = false;
              yolo26_ctx->num_classes = scores_dim2;
              printf("[YOLO26] Format: boxes [1,%d,4], scores [1,%d,%d]\n",
                     boxes_dim1, scores_dim1, scores_dim2);
          }
          else
          {
              printf("[YOLO26] ERROR: Invalid boxes dimensions [1,%d,%d], expected [1,4,N] or [1,N,4]\n",
                     boxes_dim1, boxes_dim2);
              return -1;
          }
      
          printf("[YOLO26] Predictions: %d, Classes: %d\n",
                 yolo26_ctx->num_predictions, yolo26_ctx->num_classes);
      
          return 0;
      }
      
      void yolo26_deinit_postprocess()
      {
          // Nothing to cleanup currently
      }
      
      int yolo26_post_process(rknn_app_context_t *app_ctx, yolo26_context_t *yolo26_ctx,
                              void *outputs, letterbox_t *letter_box,
                              float conf_threshold, float nms_threshold,
                              object_detect_result_list *od_results)
      {
          if (!app_ctx || !yolo26_ctx || !outputs || !letter_box || !od_results)
          {
              return -1;
          }
      
          rknn_tensor_mem **output_mems = (rknn_tensor_mem **)outputs;
      
          int model_width = app_ctx->model_width;
          int model_height = app_ctx->model_height;
      
          // Parse 2-output format
          std::vector<yolo26_detection_t> raw_detections = parse_yolo26_2output(
              output_mems,
              app_ctx->output_attrs,
              model_width, model_height,
              conf_threshold,
              yolo26_ctx->num_classes > 0 ? yolo26_ctx->num_classes : 1,
              yolo26_ctx->boxes_transposed);
      
          // Apply NMS
          std::vector<yolo26_detection_t> final_detections = yolo26_nms(raw_detections, nms_threshold);
      
          // Convert to output format with letterbox coordinate mapping
          memset(od_results, 0, sizeof(object_detect_result_list));
          int count = 0;
      
          for (const auto &det : final_detections)
          {
              if (count >= OBJ_NUMB_MAX_SIZE)
                  break;
      
              // Map coordinates back to original image space
              float x1 = det.x1 - letter_box->x_pad;
              float y1 = det.y1 - letter_box->y_pad;
              float x2 = det.x2 - letter_box->x_pad;
              float y2 = det.y2 - letter_box->y_pad;
      
              // Scale back to original coordinates
              od_results->results[count].box.left = (int)(clamp(x1, 0, model_width) / letter_box->scale);
              od_results->results[count].box.top = (int)(clamp(y1, 0, model_height) / letter_box->scale);
              od_results->results[count].box.right = (int)(clamp(x2, 0, model_width) / letter_box->scale);
              od_results->results[count].box.bottom = (int)(clamp(y2, 0, model_height) / letter_box->scale);
              od_results->results[count].prop = det.confidence;
              od_results->results[count].cls_id = det.class_id;
      
              count++;
          }
      
          od_results->count = count;
      
          return 0;
      }

      And you're good to go! 🚀

    3. Glenn JocherUltralytics(đã chỉnh sửa)

      Thanks for sharing this—splitting the head into 2 outputs (boxes + scores) is a sensible RV1106 workaround to keep RKNN-friendly ops and avoid INT8 scale/zero-point coupling issues; just note that monkey-patching head.Detect.forward is inherently version-fragile. Current Ultralytics already provides an INT8 flow for RV1106 via quantize=8 with data= calibration images (see the Rockchip RKNN export guide), so please try that first. If you still need your custom split, open a GitHub issue linking back to this thread and include !yolo checks, your rknn-toolkit2 version, and a minimal calibration set description so we can evaluate it.

  5. dttvn0010GitHub

    99ms per image is too bad. Using rknn native with 3 npu cores, I can achieve ~11ms per image

    1. Glenn JocherUltralytics

      @Arshapjoy thanks for the detailed info; for YOLO11 detection heads the export output shape is (1, nc + 4, 8400) (4 box coords plus nc class scores), so with 2 classes (1, 6, 8400) is expected and both classes are present, whereas a postprocessor assuming 5 + nc (old YOLO layout with an extra objectness channel) will effectively drop one class. I’d suggest updating your RKNN-side decoder to treat channels [0:4] as [x, y, w, h] and [4:] as class logits for all nc classes; if you still see a true (1, 7, 8400) PyTorch output on the same checkpoint, please share your ultralytics version and yolo checks output so we can dig deeper. The overall YOLO11 head behaviour is also outlined in the YOLO11 model documentation.

      @BakhtiariB the high-level YOLO("./yolo11n_rknn_model") interface is designed to keep preprocessing, NPU inference and postprocessing together, so if you need to run only the core RKNN inference on the NPU while fully controlling pre/post on the CPU you’ll need to load the exported .rknn with Rockchip’s RKNN API directly and implement your own preprocessing and YOLO11 postprocessing around it.

      @dttvn0010 the ~99 ms figure is a conservative end-to-end pipeline measurement on our RK3588 test setup, so seeing ~11 ms from a highly tuned RKNN deployment using all three NPU cores is quite reasonable; if you are open to sharing your exact model variant, quantization mode, input size and NPU core configuration, we can use that to cross-check and better explain the gap between baseline and fully optimized numbers.

      @NikolayKash in practice, large gains like that usually come from combining INT8-quantized RKNN models, all three NPU cores enabled, a suitable input resolution and very lean Python-side pre/postprocessing, so it would be great if @dttvn0010 can share their exact script and RK3588 configuration for others to replicate.

  6. guojieliGitHub

    he YOLO11 benchmark was run by the Ultralytics team on a Radxa Rock 5B based on the Rockchip RK3588, using the RKNN model format to evaluate speed and accuracy. Could you please clarify whether this was an INT8-quantized model?

  7. ArshapjoyGitHub

    Exported RKNN/ONNX model only has 1 output class instead of 2


    Overview

    I’m using Ultralytics YOLOv11s with two custom classes and exporting it to ONNX and RKNN formats. After conversion, inference on the RKNN device only detects a single class, and the output tensor shape is (1, 6, 8400) instead of the expected (1, 7, 8400). I’ve validated that the source .pt model correctly reports 2 classes, but both ONNX and RKNN exports drop one class.


    Model Details

    • Checkpoint path: path/to/yolo11s_custom.pt
    • Number of classes: 2
    • Input size: 640×640

    from ultralytics import YOLO

    Load the YOLO11 model

    model = YOLO("custom_yolo11s.pt")

    Export the model to RKNN format

    rknn_path = model.export(format="rknn", name="rk3588") print(f"RKNN model saved to: {rknn_path}")

    Actual Behavior

    • Received ONNX , RKNN and metadata.yaml after conversion
    • Exported ONNX model output shape: (1, 6, 8400)
    • Exported RKNN model output shape: (1, 6, 8400)
    • Only one class is detected during inference on the RK3588 board.

    7. Logs & Metadata

    • metadata.yaml generated alongside the RKNN model:
      model:
        name: yolo11s_custom
        format: rknn
        input_shape: [1, 3, 640, 640]
        output_shape: [1, 6, 8400]
      classes: 2
    • ONNX graph info: Attached minimal onnx.shape_inference log shows only 6 channels in the final layer.

    8. Additional Notes

    • Manual ONNX export yields the same issue, so it’s unlikely to be an Ultralytics export bug alone.
    • I’ve confirmed that the PyTorch forward pass on the .pt checkpoint produces a shape (1, 7, 8400).

    9. Request Could you please:

    1. Confirm whether there’s an option/flag in the YOLO-Ultralytics or RKNN export pipeline I’m missing to preserve all classes.
    2. Suggest any workarounds or patches to ensure correct output-channel dimensionality.
    3. Identify if this might be a known issue in RKNN-Toolkit 1.5.0 or Ultralytics YOLO v11.

    Thank you for your assistance!

  8. WeiIIzzGitHub

    Hello, when I exported the rknn model, I performed int8 quantization, but I had an error like this: E build: If set do_quantization = True, dataset file need be provided. But it`s value is None! E export_rknn: RKNN model does not exist, please load build model first! My export code is: from ultralytics import YOLO

    model = YOLO("/home/ky/dfxw/runs/detect/train3/weights/best.pt") model.export(format="rknn", name="rk3576", int8=True, data="/home/ky/rknn_yolo_test/data.yaml") The path pointed to by data is the same as the training dataset. How to solve it

    1. WeiIIzzGitHub

      The content of data.yaml is as follows path: /home/ky/dfxw/split_jiaqian # dataset root dir train: images/train val: images/val

      names: 0: 0 1: 1

    2. Glenn JocherUltralytics(đã chỉnh sửa)

      @WeiIIzz INT8 export for RKNN is supported with quantize=8 (it replaces the deprecated int8=True) together with data pointing to a dataset YAML, which Ultralytics converts into the calibration image list that RKNN needs:

      from ultralytics import YOLO
      
      model = YOLO("/home/ky/dfxw/runs/detect/train3/weights/best.pt")
      model.export(format="rknn", name="rk3576", quantize=8, data="/home/ky/rknn_yolo_test/data.yaml")

      The error you saw comes from an older version that did not pass a calibration dataset to RKNN, so run pip install -U ultralytics and retry. Make sure the YAML points to existing images. Let us know if this resolves your issue!

    3. WeiIIzzGitHub

      @glenn-jocher I followed your steps to modify the code as follows. But I still encountered the same problem.

      from ultralytics import YOLO
      
      model = YOLO("/home/ky/dfxw/runs/detect/train3/weights/best.pt")
      model.export(format="rknn", name="rk3576", int8=True, data="/home/ky/rknn_yolo_test/images")

      Is there only images in the data path?

    4. Glenn JocherUltralytics(đã chỉnh sửa)

      @WeiIIzz older releases ignored int8=True for RKNN and built the model without quantization. Current Ultralytics supports INT8 RKNN export, so after pip install -U ultralytics you can export with:

      model.export(format="rknn", name="rk3576", quantize=8, data="data.yaml")

      Here data is used for the calibration images. Without quantize, the export builds a floating-point (FP16) model.

  9. VictorAbobaGitHub

    Good day,

    Is RKNN available for obb tasks? I tried to use it directly, but got an error saying that some operations (cos) are not available in RKNN. As a fix, RKNN suggested adding disable_rules = ['reduce_reshape_op_around_concat'] to my configuration. I actually did this inside the YOLO library. Model was exported first to ONNX and then from ONNX to RKNN works and returns the responses in the format (1,6,21504), which seems what I expected. However, if I use this model through YOLO ("path_to_rknn_model", task = 'obb'), will I still get the results in the standard YOLO format? I just don't want to prescribe pre - and post-processing on my own :)

    Thank you!

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @VictorAboba thank you for your question! RKNN export now supports all seven Ultralytics tasks, including OBB, so you can export OBB models directly with format="rknn" and load the exported _rknn_model directory with YOLO(...) to get standard YOLO results without writing your own pre- and post-processing. See the Rockchip RKNN guide for details.

    2. SpidrreGitHub

      Hey! Did you notice any significant decrease in quality of your model after conversion? I am also trying to find a way to convert from OBB onnx to RKNN without 'reduce_reshape_op_around_concat'.

    3. VictorAbobaGitHub

      Hey! Did you notice any significant decrease in quality of your model after conversion? I am also trying to find a way to convert from OBB onnx to RKNN without 'reduce_reshape_op_around_concat'.

      Hello, after @glenn-jocher answer, I didn't attempt to convert the OBB model. We have a few other models, and all of them except YOLO were converted to the RKNN format. We will try using this stuff (YOLO without an NPU and others with it) ^_^ After conversion, the OCR model, for example, has almost the same quality, but it doesn't need 'reduce_reshape_op_around_concat' to be used.