Xuất Sony IMX500 cho Ultralytics YOLO11
Hướng dẫn này trình bày cách xuất và triển khai các model Ultralytics YOLOv8n và YOLO11n lên Raspberry Pi AI Camera có cảm biến Sony IMX500.
Việc triển khai model thị giác máy tính trên các thiết bị có năng lực tính toán hạn chế, chẳng hạn như Raspberry Pi AI Camera, có thể khá phức tạp. Sử dụng định dạng model được tối ưu để tăng tốc độ xử lý sẽ tạo ra khác biệt đáng kể.
Định dạng model IMX500 được thiết kế để tiêu thụ ít điện năng mà vẫn xử lý nhanh các mạng nơ-ron. Định dạng này cho phép bạn tối ưu model Ultralytics YOLO11 để chạy inference tốc độ cao, công suất thấp. Hướng dẫn này chỉ cho bạn cách xuất model sang định dạng IMX500 và triển khai lên Raspberry Pi AI Camera.
Tại sao nên xuất sang IMX500?#
Cảm biến thị giác thông minh IMX500 của Sony xử lý AI ngay trên cảm biến, điều mà Sony mô tả là lần đầu tiên trên thế giới đối với cảm biến thị giác thông minh. Cảm biến này giúp giải quyết các thách thức phổ biến của AI biên, bao gồm nút thắt cổ chai trong xử lý dữ liệu, các mối lo ngại về quyền riêng tư và những hạn chế về hiệu năng. Trong khi các cảm biến thông thường chỉ truyền hình ảnh và khung hình, IMX500 diễn giải những gì cảm biến ghi nhận, cho phép thiết bị tạo ra thông tin chuyên sâu theo thời gian thực.
Xuất Sony IMX500 cho model YOLO11#
IMX500 được thiết kế để xử lý dữ liệu trực tiếp trên cảm biến mà không cần gửi dữ liệu lên đám mây để xử lý.
IMX500 hoạt động với các model đã lượng tử hóa. Lượng tử hóa giúp model nhỏ hơn và nhanh hơn mà không làm giảm nhiều độ chính xác. Cách này phù hợp với tài nguyên hạn chế của điện toán biên, giúp ứng dụng phản hồi nhanh nhờ giảm độ trễ và xử lý dữ liệu nhanh tại chỗ mà không phụ thuộc vào đám mây. Xử lý cục bộ cũng bảo vệ quyền riêng tư và bảo mật dữ liệu người dùng vì dữ liệu không được gửi đến máy chủ từ xa.
Các tính năng chính của IMX500:
- Đầu ra metadata: Thay vì chỉ truyền hình ảnh, IMX500 có thể xuất cả hình ảnh lẫn metadata (kết quả suy luận), hoặc chỉ xuất metadata để giảm kích thước dữ liệu, giảm băng thông và hạ chi phí.
- Giải quyết lo ngại về quyền riêng tư: Bằng cách xử lý dữ liệu trên thiết bị, IMX500 giải quyết các lo ngại về quyền riêng tư và phù hợp với những ứng dụng lấy con người làm trung tâm như đếm người và theo dõi tình trạng sử dụng không gian.
- Xử lý theo thời gian thực: Khả năng xử lý nhanh trên cảm biến hỗ trợ đưa ra quyết định theo thời gian thực cho các ứng dụng AI biên như hệ thống tự hành.
Trước khi bắt đầu: Để đạt kết quả tốt nhất, hãy đảm bảo model YOLO11 đã được chuẩn bị kỹ lưỡng để xuất bằng cách làm theo Hướng dẫn huấn luyện model, Tổng quan về tập dữ liệu và Hướng dẫn tinh chỉnh siêu tham số của chúng tôi.
Các tác vụ được hỗ trợ#
Xuất IMX500 hỗ trợ bốn trong số bảy tác vụ của Ultralytics và chỉ áp dụng cho YOLOv8n và YOLO11n: các họ model, kích thước và kiến trúc khác không được hỗ trợ; việc xuất model phân đoạn ngữ nghĩa, OBB hoặc ước tính độ sâu sẽ gây ra lỗi.
Ví dụ sử dụng#
Xuất model Ultralytics YOLO11 sang định dạng IMX500 và chạy suy luận bằng model đã xuất.
Định dạng IMX500 hỗ trợ các chế độ Export, Predict và Validate. Inference và validation của Ultralytics chạy model_imx.onnx đã export trên CPU của host.
Inference ở đây chỉ xác nhận rằng model đã xuất hoạt động như mong đợi trước khi triển khai lên Raspberry Pi AI Camera.
from ultralytics import YOLO
# Tải model PyTorch YOLO11n
model = YOLO("yolo11n.pt")
# # Xuất model
model.export(format="imx", data="coco8.yaml") # mặc định xuất với lượng tử hóa PTQ
# Tải model đã xuất
imx_model = YOLO("yolo11n_imx_model")
# Chạy suy luận
results = imx_model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# Tải model PyTorch YOLO11n-pose
model = YOLO("yolo11n-pose.pt")
# # Xuất model
model.export(format="imx", data="coco8-pose.yaml") # mặc định xuất với lượng tử hóa PTQ
# Tải model đã xuất
imx_model = YOLO("yolo11n-pose_imx_model")
# Chạy suy luận
results = imx_model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# Tải model PyTorch YOLO11n-cls
model = YOLO("yolo11n-cls.pt")
# # Xuất model
model.export(format="imx", data="imagenet10") # mặc định xuất với lượng tử hóa PTQ
# Tải model đã xuất
imx_model = YOLO("yolo11n-cls_imx_model")
# Chạy suy luận
results = imx_model("https://ultralytics.com/images/bus.jpg", imgsz=224)from ultralytics import YOLO
# Tải model PyTorch YOLO11n-seg
model = YOLO("yolo11n-seg.pt")
# # Xuất model
model.export(format="imx", data="coco8-seg.yaml") # mặc định xuất với lượng tử hóa PTQ
# Tải model đã xuất
imx_model = YOLO("yolo11n-seg_imx_model")
# Chạy suy luận
results = imx_model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# Tải model IMX500 đã xuất
model = YOLO("yolo11n_imx_model")
# # Đánh giá độ chính xác trên bộ dữ liệu COCO8
metrics = model.val(data="coco8.yaml")Việc xuất IMX chỉ được hỗ trợ trên Linux với Python 3.10–3.12 và yêu cầu Java 17 trở lên. Gói Ultralytics cài đặt các dependency xuất bổ sung trong thời gian chạy. Khi chạy lệnh xuất lần đầu, bạn có thể cần khởi động lại terminal để đảm bảo lệnh hoạt động chính xác.
Các tham số xuất model#
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
format | str | 'imx' | Đị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. |
imgsz | int hoặc tuple | 640 | Kích thước ảnh mong muốn cho đầu vào model. Có thể là số nguyên cho ảnh vuông hoặc tuple (height, width) để chỉ định kích thước cụ thể. |
quantize | int hoặc str | 8/auto | Độ chính xác lượng tử hóa. 8 (INT8/PTQ) là bắt buộc và được tự động bật cho IMX500. Không hỗ trợ chỉ xuất FP32 và FP16. Thay thế các flag half/int8 đã lỗi thời. |
data | str | None | Đường dẫn đến YAML của dataset, cần thiết cho quá trình lượng tử hóa; riêng tác vụ phân loại cần thư mục dataset hoặc tên dataset tích hợp sẵn. Nếu không chỉ định, Ultralytics sẽ chọn dataset hiệu chuẩn mặc định cho tác vụ của model. |
fraction | float, int hoặc list | 1.0 | Tập con hiệu chuẩn dưới dạng tỷ lệ, số lượng ảnh hoặc tỷ lệ/số lượng [train, val, test]. Danh sách gồm hai mục giữ test ở dạng đầy đủ, còn 0 sẽ bỏ qua mục này. |
nms | bool, không bắt buộc | None | Chọn đầu ra thô (None, mặc định), NMS tích hợp (True) hoặc head không dùng NMS (False). IMX yêu cầu nms=True cho detect, segment và pose, đồng thời tự động chọn tùy chọn này. |
device | str | None | Chỉ định thiết bị dùng để xuất: GPU (device=0), CPU (device=cpu). |
Để biết thêm chi tiết về quy trình xuất, hãy truy cập trang tài liệu Ultralytics về xuất model.
Quá trình xuất tạo một thư mục có tên <model-name>_imx_model. Thư mục này chứa model_imx.onnx để xác thực lượng tử hóa và tệp packerOut.zip, cần thiết để đóng gói model triển khai trên phần cứng IMX500. Ngoài ra, thư mục <model-name>_imx_model sẽ chứa một tệp văn bản (labels.txt) liệt kê tất cả nhãn liên quan đến model.
yolo11n_imx_model
├── dnnParams.xml
├── labels.txt
├── packerOut.zip
├── model_imx.onnx
├── model_imx_MemoryReport.json
└── model_imx.pbtxtSử dụng xuất IMX500 khi triển khai#
Sau khi xuất model Ultralytics YOLO11n sang định dạng IMX500, bạn có thể triển khai model lên Raspberry Pi AI Camera để chạy inference.
Yêu cầu phần cứng#
Đảm bảo bạn có phần cứng sau:
- Raspberry Pi 5 hoặc Raspberry Pi 4 Model B
- Camera Raspberry Pi AI
Kết nối Raspberry Pi AI Camera với đầu nối MIPI CSI 15 chân trên Raspberry Pi, sau đó bật nguồn Raspberry Pi.
Yêu cầu phần mềm#
Hướng dẫn này đã được kiểm thử với Raspberry Pi OS Bookworm chạy trên Raspberry Pi 5.
Bước 1: Mở cửa sổ terminal và chạy các lệnh sau để cập nhật phần mềm Raspberry Pi lên phiên bản mới nhất.
sudo apt update && sudo apt full-upgradeBước 2: Cài đặt firmware IMX500 cần thiết để vận hành cảm biến IMX500.
sudo apt install imx500-allBước 3: Khởi động lại Raspberry Pi để áp dụng các thay đổi.
sudo rebootBước 4: Cài đặt thư viện module ứng dụng AITRIOS cho Raspberry Pi
pip install git+https://github.com/SonySemiconductorSolutions/aitrios-rpi-application-module-library.gitBước 5: Chạy phát hiện đối tượng, ước tính pose, phân loại và phân đoạn YOLO11 bằng các script sau, có trong các ví dụ của thư viện module ứng dụng aitrios-rpi.
Đảm bảo thay thế các thư mục model_file và labels.txt cho phù hợp với môi trường của bạn trước khi chạy các script này.
import numpy as np
from modlib.apps import Annotator
from modlib.devices import AiCamera
from modlib.models import COLOR_FORMAT, MODEL_TYPE, Model
from modlib.models.post_processors import pp_od_yolo_ultralytics
class YOLO(Model):
"""YOLO model for IMX500 deployment."""
def __init__(self):
"""Initialize the YOLO model for IMX500 deployment."""
super().__init__(
model_file="yolo11n_imx_model/packerOut.zip", # replace with proper directory
model_type=MODEL_TYPE.CONVERTED,
color_format=COLOR_FORMAT.RGB,
preserve_aspect_ratio=False,
)
self.labels = np.genfromtxt(
"yolo11n_imx_model/labels.txt", # replace with proper directory
dtype=str,
delimiter="\n",
)
def post_process(self, output_tensors):
"""Post-process the output tensors for object detection."""
return pp_od_yolo_ultralytics(output_tensors)
device = AiCamera(frame_rate=16) # Optimal frame rate for maximum FPS of the YOLO model running on the AI Camera
model = YOLO()
device.deploy(model)
annotator = Annotator()
with device as stream:
for frame in stream:
detections = frame.detections[frame.detections.confidence > 0.55]
labels = [f"{model.labels[class_id]}: {score:0.2f}" for _, score, class_id, _ in detections]
annotator.annotate_boxes(frame, detections, labels=labels, alpha=0.3, corner_radius=10)
frame.display()Benchmark#
Các benchmark YOLOv8n, YOLO11n, YOLOv8n-pose, YOLO11n-pose, YOLOv8n-cls và YOLO11n-cls dưới đây được nhóm Ultralytics thực hiện trên Raspberry Pi AI Camera bằng định dạng model imx để đo tốc độ và độ chính xác.
| Model | Định dạng | Kích thước (pixel) | Kích thước của packerOut.zip (MB) | mAP50-95(B) | Thời gian suy luận (ms/ảnh) |
|---|---|---|---|---|---|
| YOLOv8n | imx | 640 | 2.1 | 0.470 | 58.79 |
| YOLO11n | imx | 640 | 2.2 | 0.517 | 58.82 |
| YOLOv8n-pose | imx | 640 | 2.0 | 0.687 | 58.79 |
| YOLO11n-pose | imx | 640 | 2.1 | 0.788 | 62.50 |
| Model | Định dạng | Kích thước (pixel) | Kích thước của packerOut.zip (MB) | độ chính xác (top1) | độ chính xác (top5) | Thời gian suy luận (ms/ảnh) |
|---|---|---|---|---|---|---|
| YOLOv8n-cls | imx | 224 | 2.3 | 0.25 | 0.5 | 33.31 |
| YOLO11n-cls | imx | 224 | 2.3 | 0.25 | 0.417 | 33.31 |
Việc xác thực các kết quả benchmark trên được thực hiện bằng tập dữ liệu COCO128 cho model phát hiện, tập dữ liệu COCO8-Pose cho model ước tính pose và ImageNet10 cho model phân loại.
Có gì bên trong?#
Bộ công cụ nén model Sony (MCT)#
Bộ công cụ nén model (MCT) của Sony là bộ công cụ tối ưu model deep learning thông qua lượng tử hóa và cắt tỉa. Bộ công cụ hỗ trợ nhiều phương pháp lượng tử hóa và cung cấp các thuật toán tiên tiến để giảm kích thước model cũng như độ phức tạp tính toán mà không làm giảm đáng kể độ chính xác. MCT đặc biệt hữu ích khi triển khai model trên các thiết bị có tài nguyên hạn chế, giúp inference hiệu quả và giảm độ trễ.
Các tính năng được MCT hỗ trợ#
MCT của Sony cung cấp nhiều tính năng được thiết kế để tối ưu model mạng nơ-ron:
- Tối ưu hóa đồ thị: Chuyển đổi model thành các phiên bản hiệu quả hơn bằng cách gộp các lớp như chuẩn hóa theo batch vào các lớp đứng trước.
- Tìm kiếm tham số lượng tử hóa: Giảm thiểu nhiễu lượng tử hóa bằng các metric như Sai số bình phương trung bình, Không cắt ngưỡng và Sai số tuyệt đối trung bình.
- Thuật toán lượng tử hóa nâng cao:
- Hiệu chỉnh giá trị âm bị dịch chuyển: Khắc phục các vấn đề về hiệu năng do lượng tử hóa activation đối xứng gây ra.
- Lọc giá trị ngoại lai: Sử dụng z-score để phát hiện và loại bỏ các giá trị ngoại lai.
- Phân cụm: Sử dụng lưới lượng tử hóa không đồng nhất để khớp phân phối tốt hơn.
- Tìm kiếm độ chính xác hỗn hợp: Gán độ rộng bit lượng tử hóa khác nhau cho từng lớp dựa trên độ nhạy.
- Trực quan hóa: Sử dụng TensorBoard để quan sát thông tin chuyên sâu về hiệu năng model, các giai đoạn lượng tử hóa và cấu hình độ rộng bit.
Lượng tử hóa#
MCT hỗ trợ một số phương pháp lượng tử hóa để giảm kích thước model và cải thiện tốc độ suy luận:
- Lượng tử hóa sau huấn luyện (PTQ):
- Có thể sử dụng thông qua API Keras và PyTorch.
- Độ phức tạp: Thấp
- Chi phí tính toán: Thấp (vài phút trên CPU)
- Lượng tử hóa sau huấn luyện dựa trên gradient (GPTQ):
- Có thể sử dụng thông qua API Keras và PyTorch.
- Độ phức tạp: Trung bình
- Chi phí tính toán: Vừa phải (2-3 giờ GPU)
- Huấn luyện nhận biết lượng tử hóa (QAT):
- Độ phức tạp: Cao
- Chi phí tính toán: Cao (12-36 giờ GPU)
MCT cũng hỗ trợ nhiều lược đồ lượng tử hóa cho trọng số và activation:
- Lũy thừa của hai (thân thiện với phần cứng)
- Đối xứng
- Đồng nhất
Cắt tỉa có cấu trúc#
MCT giới thiệu phương pháp cắt tỉa model có cấu trúc, nhận biết phần cứng và được thiết kế cho các kiến trúc phần cứng cụ thể. Kỹ thuật này tận dụng các khả năng Single Instruction, Multiple Data (SIMD) của nền tảng đích bằng cách cắt tỉa các nhóm SIMD. Cách làm này giảm kích thước và độ phức tạp của model, đồng thời tối ưu mức sử dụng kênh, phù hợp với kiến trúc SIMD để sử dụng tài nguyên có mục tiêu cho dung lượng bộ nhớ trọng số. Tính năng này có trong API Keras và PyTorch.
Công cụ chuyển đổi IMX500 (trình biên dịch)#
IMX500 Converter Tool là thành phần thiết yếu của bộ công cụ IMX500, cho phép biên dịch model để triển khai trên cảm biến IMX500 của Sony (ví dụ: Raspberry Pi AI Camera). Công cụ biên dịch các model Ultralytics YOLO11 đã lượng tử hóa sang dạng có thể chạy hiệu quả trên phần cứng đích. Sau khi lượng tử hóa, quá trình xuất tạo các tệp nhị phân chứa dữ liệu model và cấu hình dành riêng cho thiết bị, cần thiết để triển khai lên Raspberry Pi AI Camera.
Các trường hợp sử dụng thực tế#
Xuất sang định dạng IMX500 có thể được ứng dụng rộng rãi trong nhiều ngành. Dưới đây là một số ví dụ:
- AI biên và IoT: Cho phép phát hiện đối tượng trên drone hoặc camera an ninh, nơi việc xử lý theo thời gian thực trên thiết bị công suất thấp là thiết yếu.
- Thiết bị đeo: Triển khai các model được tối ưu hóa cho xử lý AI quy mô nhỏ trên thiết bị đeo theo dõi sức khỏe.
- Thành phố thông minh: Sử dụng model YOLO11 được xuất sang IMX500 để giám sát giao thông và phân tích an toàn với tốc độ xử lý nhanh hơn và độ trễ tối thiểu.
- Phân tích bán lẻ: Tăng cường giám sát trong cửa hàng bằng cách triển khai các model được tối ưu hóa trong hệ thống điểm bán hàng hoặc kệ hàng thông minh.
Kết luận#
Xuất model Ultralytics YOLO11 sang định dạng IMX500 của Sony cho phép bạn triển khai model để chạy inference hiệu quả trên camera dùng IMX500. Lượng tử hóa giảm kích thước model và tăng tốc độ inference, chỉ làm giảm nhẹ độ chính xác.
Để biết thêm thông tin và hướng dẫn chi tiết, hãy tham khảo trang web IMX500 của Sony.
Câu hỏi thường gặp#
Để xuất model YOLO11 sang định dạng IMX500, hãy sử dụng API Python hoặc lệnh CLI:
from ultralytics import YOLO model = YOLO("yolo11n.pt") model.export(format="imx") # Xuất với lượng tử hóa PTQ theo mặc địnhQuy trình xuất sẽ tạo một thư mục chứa các tệp cần thiết để triển khai, bao gồm
packerOut.zip.Định dạng IMX500 mang lại một số ưu điểm quan trọng khi triển khai ở biên:
- Xử lý AI trên chip giúp giảm độ trễ và mức tiêu thụ điện năng
- Xuất cả hình ảnh và metadata (kết quả suy luận) thay vì chỉ xuất hình ảnh
- Tăng cường quyền riêng tư nhờ xử lý dữ liệu cục bộ mà không phụ thuộc vào đám mây
- Khả năng xử lý theo thời gian thực, lý tưởng cho các ứng dụng nhạy cảm về thời gian
- Lượng tử hóa được tối ưu hóa để triển khai model hiệu quả trên các thiết bị có tài nguyên hạn chế
Để triển khai model IMX500, bạn cần:
Phần cứng:
- Raspberry Pi 5 hoặc Raspberry Pi 4 Model B
- Raspberry Pi AI Camera có cảm biến IMX500
Phần mềm:
- Raspberry Pi OS Bookworm
- Firmware và công cụ IMX500 (
sudo apt install imx500-all)
Dựa trên các bài benchmark của Ultralytics trên Raspberry Pi AI Camera:
- YOLO11n đạt thời gian suy luận 58.82ms cho mỗi hình ảnh
- mAP50-95 đạt 0.517 trên dataset COCO128
- Kích thước model chỉ 2.2MB sau khi lượng tử hóa
Điều này cho thấy định dạng IMX500 cung cấp khả năng suy luận thời gian thực hiệu quả, đồng thời duy trì độ chính xác tốt cho các ứng dụng AI biên.
Bình luận86
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
Chad Walshwhere is the best place to get support on the IMX500. I am running into multiple issues: i. my first yolo11n model built fine and exported to imx500, no problem, but my second model with a LOT more training images build fine but crashed the imx500 export. ii. the output of the imx500 during inference is giving a lot of none outputs between solid recognitions. it seems like there is something interfering with or disrupting the inference outputs (e.g., good output, none, none, none, none, good output, ...). where is the best place to get help with these issues?
Glenn JocherUltralyticsPlease continue the discussion here so the Ultralytics team can help; for the export crash, share the exact export command, full text traceback, and output from
yolo checks, and for intermittentNoneresults include a minimal inference script, confidence threshold, and a short reproducible input sample. Note that IMX export uses the calibration dataset specified bydataand defaults to the full dataset, so testing a smallerfractionmay help isolate resource-related failures.
leeprevost
I've made considerable progress by moving conducting this model compression process with a Container using dtcooper/raspberrypi-os:python3.11 after considerable problems with dependencies. Now getting a container most of the way through the process of compressing my yolov11s model and its trained best.pt weights.
At the end of the process - I get a simple "killed" after the Calculation of quantization parameters step. I see memory spiking close to 100% on top and think I'm hitting OOM with my pi4 8gb.
root@a5e132f6b333:/app# yolo export model=./models/yolov11/best.pt data='Billfish-Breeds-1/data.yaml' format=imx verbos> Ultralytics 8.3.221 🚀 Python-3.11.14 torch-2.9.0+cpu CPU (aarch64) WARNING ⚠️ IMX export requires nms=True, setting nms=True. YOLO11s summary (fused): 100 layers, 9,413,187 parameters, 0 gradients, 21.3 GFLOPs PyTorch: starting from 'models/yolov11/best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) ((1, 8400, 4> IMX: collecting INT8 calibration images from 'data=Billfish-Breeds-1/data.yaml' Fast image access ✅ (ping: 0.1±0.0 ms, read: 16.1±2.7 MB/s, size: 16.4 KB) Scanning /app/Billfish-Breeds-1/valid/labels.cache... 268 images, 0 backgrounds, 0 corrupt: 100% ━━━━━━━━━━━━ 268/268 1> WARNING ⚠️ IMX: >300 images recommended for INT8 calibration, found 268 images. IMX: starting export with model_compression_toolkit 2.4.4... representative_data_gen generates a batch size of 1 which can be slow for optimization: consider increasing the batch s> WARNING:Model Compression Toolkit:OperatorSetNames.DEPTHWISE_CONV is not in model. Statistics Collection: 268it [1:01:26, 13.76s/it] Calculating quantization parameters: 100%|█████████████████████████████████████████████████████| 294/294 [12:44<00:00, > KilledWould appreciate any suggestion around this but think it probably pushes me over the edge to order my pi5? Or do I try to train on the yolov8 or yolov11n? I've not had very good success with the nano models. I've convinced myself the tradeoffs to the small is well worth it but that may be incompatible with this process?
leeprevost
@glenn-jocher am I posting at the right place? Put this in issues on gh?
Glenn JocherUltralytics@leeprevost you’re in the right place for discussion, but the OOM during IMX export is a new issue—please open a new issue for visibility. In the issue, include: the exact export command and full log,
yolo checksoutput (orultralytics.utils.checks.collect_system_info()), Java version (java --version), and the versions of IMX toolchain (pip freeze | grep -E "imx500|model-compression|sony-custom"). As immediate workarounds: export on a Linux x86_64 machine with more RAM, target YOLO11n/YOLOv8n (the IMX path is tuned for “n” models), and reduce calibration load withfraction(e.g., 0.25). Example:yolo export model=best.pt format=imx data=your.yaml imgsz=640 fraction=0.25IMX-specific knobs are summarized in the IMX500 export arguments here: Sony IMX500 export guide – Export arguments, and the exporter function requirements here: export_imx reference.
leeprevost
Thank you. I'll dig into the logs and see if I can add anything before opening new issue.
leeprevost
a few more questions and I will open an issue:
- Note that I was using a model trained on yolov11s rather than n as I've seen large degradation in the number of false positives in my model.
- I assume by "full log" you mean the output from the yolo export command with verbose at default (true). In other words, what I posted above?
- For some reason, I thought I read int he docs that i had to perform the model compression on the target machine. for me, the ultimate target is RpiZero2 but no way the model will export on that footprint . so, I went to the largest pi I have which is a Rpi4 -- that resulted in the OOM. So, am unsure by your guidance pointing me to the larger x86 linux machine. How will the process know the device limits if I perform it on that?
Trying to read these guides as best I can. I have not spent much time on the Sony site yet. If you'll point me, I don't want to start an issue that isn't an issue.
leeprevost
I opened an issue: https://github.com/ultralytics/ultralytics/issues/22512
Just tried the export again with the fraction=0.25 argument and got to "Optimal Solution Found" with objective measure of 0.94, then died with error:
Error x IMX: export failure 12662.7s: No module named 'onnxscript'
leeprevost
https://github.com/pytorch/pytorch/issues/166352 -- adding to my requirements.txt pointed to by Containerfile.
Glenn JocherUltralytics(đã chỉnh sửa)@leeprevost great progress. IMX export/quantization does not need to run on the target; it cross-compiles for IMX500, so doing it on a larger Linux host is recommended. “Full log” means the complete stdout/stderr from the export run.
The “No module named 'onnxscript'” failure is a missing dependency. Current Ultralytics installs the IMX toolchain (including
imx500-converterandmodel-compression-toolkit) itself, so upgrade withpip install -U ultralyticsand re-run the export rather than pinning old versions by hand. Let’s continue the deep-dive in the issue you opened for traceability.leeprevost
Ok -- @glenn-jocher: am moving this to my opened issue. Still trying this on my pi4 but can move to my dev machine with plenty of RAM + Cuda. Got further but still died with a torch error -- will post there.
Glenn JocherUltralyticsThanks—let’s continue in the issue for traceability. On the larger Linux host, try GPU-assisted export to reduce RAM pressure and speed up calibration; if needed, temporarily lower
imgszto validate the pipeline:yolo export model=path/to/best.pt format=imx data=path/to/data.yaml device=0 imgsz=640 # if memory is still tight during calibration yolo export model=path/to/best.pt format=imx data=path/to/data.yaml device=0 imgsz=512For a concise list of export options and behavior, see the Export mode docs at Ultralytics YOLO — Export.
leeprevost
Much thanks for posting this guide. Thank you.
I am having very solid success running the standard detection models right out of the box on the RpiZero 2 which is my target platform. I'm actually amazed at the power draw (ran detection/streaming for about 175 minutes on a 4400mahr battery using about 60% of its capacity). Also, very solid top/htop scores showing less than 1/8 of CPU utilization. Memory is still such a problem on a rpiz2 but not any more so than what is being used with streaming only on the pi. Still have about 50% of memory left over as I recall. I've got screen shots of top screens if needed.
But, I need to get a trained model working on my RpiZ2 and am running into problems. As the guide seemed to indicate (or perhaps Sony's), I need to do most of the quantization on my target platform. I assumed that meant my zero. I have a very good model trained with yolov11m or large. I've tried to reduce that to a nano but I'm getting too much loss of MAP scores and too much false positive rates. So, am now trying to get a yolov11s to work. On my quantization process (it was not clear how to do this with a custom model) but am first loading the yolov11s.pt and then loading my best.pt on top of that. Ultralytics successfully loads my data, gives me a warning prompt about my 290 images (< 300 not ideal) and then another about processing speed with 1 batch. The program then goes off the rails with no UI messages. I assume I'm running out of memory on the piz2. So, my next steps seem to be either:
- Start over and try with nano model.
- Do my quantization on a larger pi (i've got a spare pi4).
I guess another option would be to spend more time understanding Sony's under the hood tools to optimize those settings?
Would appreciate some guidance here down the right path.
leeprevost
One thing that would be very helpful is to show how to do this on something other than the target platform. i'm trying to get a small detection model to run on a rpi zero2 and hate to have to download all of my training data to the zero to do the quantization.
Idea: Have a step that allows collection of the "target_platform_capabilities" information using Sony's model compression toolkit you are using under the hood, pickle it, and then use that object to drive the model compression on a larger machine.
I could probably dig in and try to follow your code and follow the "imx" part of your export process...
bohlebots
Wie schaffe ich es, dass das Modell im Speicher des IMX500 bleibt? Die PICAM wurde ja angepriesen mit der Aussage, dass sie selbst an einem Pi zero-2 mit gleicher Geschwindigkeit läuft und in der Tat, das täte sie, aber das Modell muss jedes Mal neu aufgeladen werden, und das dauert beim Pi Zero ewig, ja selbst mit einem Pi5 dauert es Minuten. Grundsätzlich muss die imx500 aber ein Modell auch bei ausgeschaltetem Strom im Speicher halten können, so dass nach dem Anschalten das letzte Modell direkt zur Verfügung steht. Wie bekomme ich das hin?
Gruß Roland
Teo-treny
Hello ! When running object detection (step 5), I get the following error :
Exception in thread Thread-2 (_process_requests_func): Traceback (most recent call last): File "/home/pi/.pyenv/versions/3.11.9/lib/python3.11/threading.py", line 1045, in _bootstrap_inner self.run() File "/home/pi/.pyenv/versions/3.11.9/lib/python3.11/threading.py", line 982, in run self._target(*self._args, **self._kwargs) File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/devices/ai_camera/ai_camera.py", line 193, in _process_requests_func callback() File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/devices/ai_camera/ai_camera.py", line 207, in _process_requests self._parse_request(req) File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/devices/ai_camera/ai_camera.py", line 256, in _parse_request detections = self.model.post_process(outputs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/pi/Desktop/imx_test/Test_1.py", line 23, in post_process return pp_od_yolo_ultralytics(output_tensors) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/models/post_processors/post_processors.py", line 129, in pp_od_yolo_ultralytics n_detections = int(output_tensors[3]) ^^^^^^^^^^^^^^^^^^^^^^ TypeError: only length-1 arrays can be converted to Python scalarsI'm running Python 3.11.9 and installed all the dependencies following the guide. My Raspberry PI is a 3B+ model with Bookworm 64 bits and is up to date.
aytacsekmen
In the official IMX500 documentation provided by Sony (https://developer.sony.com/tinyml-23/developer-tools/documentation/imx500-evaluation-kit-user-guide?version=2023-11-28&progLang=), they describe the process of generating the network.fpk and network_info.txt files that will be used to deploy the model to IMX500, using the Packager.sh script. However, when I attempt to apply the same procedure to the packerOut.zip file I created by following the tutorial on https://docs.ultralytics.com/integrations/sony-imx500, I am unable to run the model on the IMX500. Also I couldn't run your implementation because it says that some packages are not found which I believe is related to the version of the OS. Currently I use the Pi OS that is provided by SONY for compatibility issues. I could run some other deep learning models following the steps in the (https://developer.sony.com/tinyml-23/developer-tools/documentation/imx500-evaluation-kit-user-guide?version=2023-11-28&progLang=), but I believe, there must be something different related to the creation of packerOut.zip file.
Could you assist in resolving this issue with the conversion process? @glenn-jocher
HelloCigar
Hello, per picamera2 docs, creating apps with "a camera window embedded into the GUI is through Qt", is there no other way to embed the video feed in other GUI frameworks?
skim-sony
Hi, I followed the steps in this page to convert the yolov8n model with imx500 converter and tested it with raspberry ai camera. But I get 29.5 ms for the inference time with 640x640 input tensor size. So I wonder why my inference time is better than your result (58.82ms). Which version of imx500 converter did you use?
skim-sony
Also, how did you measure the inference time? Did you use imx500.get_kpi_info(metadata) or calculate the elapsed time of picam2.capture_metadata()?
Glenn JocherUltralytics(đã chỉnh sửa)@skim-sony congratulations on the faster result! Our documented figure (58.82 ms for YOLO11n, see the Benchmarks) was measured by the Ultralytics team on a Raspberry Pi AI Camera with the
imxformat. Differences can come from the converter version, firmware, hardware (Pi 5 vs Pi 4) or how the time is measured. Would you mind sharing which converter version and Raspberry Pi model you're using? This could help other community members.skim-sony(đã chỉnh sửa)
Hi, I have used Pi5 and tried both 3.14.3 and 3.16.1 for imx500-converter. And both produces 29.5ms for inference time. It seems like you also use Pi5, so I wonder why our results are different. I'd like to reproduce your results 58.82 ms to learn what improves the inference time. So it would be helpful if you could share some info how to sync with your environment. Thanks!
Glenn JocherUltralytics(đã chỉnh sửa)@skim-sony that's interesting you're seeing better performance! The discrepancy could be due to several factors:
- Measurement methodology: end-to-end time (pre/post-processing + inference) differs from model-only inference time
- Firmware and converter versions
- Image resolution and resizing
- Test conditions: background processes, temperature, and power settings
Our published numbers are in the Benchmarks. If you'd like to share more details about your implementation, the community would certainly benefit.
fracipriano
Hello, I'm trying to run the standard YOLOv8n model on a Raspberry Pi AI Camera. I followed the exemple in the documentation
from ultralytics import YOLO # Load a YOLOv8n PyTorch model model = YOLO("yolov8n.pt") # Export the model model.export(format="imx", data="coco8.yaml") # exports with PTQ quantization by default # Load the exported model imx_model = YOLO("yolov8n_imx_model") # Run inference results = imx_model("https://ultralytics.com/images/bus.jpg")I got a bunch of warnings during the execution (export_log.txt), but the imx_model seemed to work properly in the end.
I then packaged it via IMX500 Packager and test it using the imx500_object_detection_demo.py. The Network Firmware gets uploaded, the application starts, but I get no detection. I tried to lower the detection threshold, but it didn't help. Any idea on what could be the problem? Any suggestion would be much appreciated.
Glenn JocherUltralyticsThank you for the detailed issue. Let's troubleshoot step by step. First, ensure your Raspberry Pi AI Camera is correctly connected and recognized by running
libcamera-helloin the terminal. If the camera works, verify that thelabels.txtpath in your demo command matches the exported file. You can also try inference on a static image first withimx_model.predict("test.jpg")to isolate live feed issues. For further assistance, please share the full export log and a screenshot of your camera output.For additional guidance, refer to the Sony IMX500 and AITRIOS integration blog post which demonstrates successful deployment steps.
fracipriano
Hello @glenn-jocher,
libcamera-hello works fine as does the imx500_object_detection_demo.py when using the default model ("/usr/share/imx500-models/imx500_network_ssd_mobilenetv2_fpnlite_320x320_pp.rpk").
There seems to be no problem with the labels.txt file as, if a run the imx500_object_detection_demo.py specifying the path to my label.txt, it works fine.
The imx_model also works fine before the packaging.
Here a screenshot of the camera output:
You can find the full export log file in my first post. Do you think any of the errors and/or warnings there could cause any problem with the packaging process via the IMX500-Packager?
Glenn JocherUltralyticsThank you for sharing these details. The warnings in your export log about "No BN layers to fold" and quantization parameters are normal during IMX conversion and shouldn't affect packaging. Since your camera feed works with the default model but not your custom export, please verify:
- Your
imx500-packagecommand uses the exactpackerOut.zipfromyolov8n_imx_model - The input tensor shape in your exported model matches IMX500 expectations (640x640 by default)
If issues persist, we recommend trying the IMX500 conversion process with our pretrained YOLOv8n model from https://github.com/ultralytics/assets/releases as a validation step.
- Your
fracipriano
Hello @glenn-jocher , thank you for your answer.
- Yes, I'm the one specifying the packerOut.zip path when running imx500-package
- I think so. Here is the content of the dnnParams.xml file generated by the export function
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <dnnParams> <networks> <network name="yolov8n_new_imx" ordinal="0" type=""> <inputTensors> <inputTensor persistency="0" ordinal="0" name="Placeholder.input.uid1:0" l2Offset="260480" numOfDimensions="3" bitsPerElement="8" shift="0" scale="0.00390625" format="unsigned"> <dimensions> <dimension size="3" serializationOrder="2" ordinal="0" padding="0"/> <dimension size="640" serializationOrder="1" ordinal="1" padding="0"/> <dimension size="640" serializationOrder="0" ordinal="2" padding="0"/> </dimensions> </inputTensor> </inputTensors> <outputTensors> <outputTensor ordinal="1" name="transform-83-/MultiClassNMS:0" l2Offset="281984" numOfDimensions="1" bitsPerElement="8" shift="0" scale="0.00390625" format="unsigned"> <dimensions> <dimension size="300" serializationOrder="0" ordinal="0" padding="0"/> </dimensions> </outputTensor> <outputTensor ordinal="2" name="transform-84-/MultiClassNMS:0" l2Offset="280960" numOfDimensions="1" bitsPerElement="16" shift="0" scale="1.0" format="signed"> <dimensions> <dimension size="300" serializationOrder="0" ordinal="0" padding="0"/> </dimensions> </outputTensor> <outputTensor ordinal="3" name="transform-85-/MultiClassNMS:0" l2Offset="279936" numOfDimensions="1" bitsPerElement="16" shift="0" scale="1.0" format="signed"> <dimensions> <dimension size="1" serializationOrder="0" ordinal="0" padding="0"/> </dimensions> </outputTensor> <outputTensor ordinal="0" name="transform-86-/MultiClassNMS:0" l2Offset="260480" numOfDimensions="2" bitsPerElement="16" shift="0" scale="0.03125" format="signed"> <dimensions> <dimension size="300" serializationOrder="0" ordinal="0" padding="0"/> <dimension size="4" serializationOrder="1" ordinal="1" padding="0"/> </dimensions> </outputTensor> </outputTensors> </network> </networks> <l2memory totalSize="8388480" coefficientsSize="2604544" reservedMemorySize="1024" networksRuntimeSize="5523456"/> </dnnParams>I downloaded the yolov8n.pt file from the Sep 29, 2024 Release and repeated the process from the beginning. Same result.
I'm adding here the terminal outputs I get when running the imx500-package: imx500-package_log.txt
Glenn JocherUltralytics(đã chỉnh sửa)Thanks for sharing the details. The
dnnParams.xmlshows correct 640x640 input dimensions. Since the default Mobilenet model works but your YOLOv8 export doesn't, please verify that your output tensor dimensions and ordering match the demo's expectations. YOLO IMX exports have a different output layout from Mobilenet, so the demo's post-processing must match. The deployment section of the IMX500 guide uses thepp_od_yolo_ultralyticspost-processor from the AITRIOS module library for Ultralytics YOLO IMX exports.fracipriano
Okay. So the problem was actually related to the output. The ordering is fine, as the scores and the classes. The problem are the bboxes. The values that I obtain are completely out of scale.
Example:
detection label: cup (0.56) detection box: (396100, 107520, 0, 0)whereas I would expect something like this:
detection label: cup (0.56) detection box: (39, 459, 440, 177)I'm not sure how to interpret this results. Is (396100, 107520, 0, 0) supposed to be the raw output of YOLOv8n? Also, in the dnnParams.xml posted above, I see that there is a scale="0.00390625" associated with the component of the output tensor relative to the bboxes. Should I renormalize my output using this factor?
Thank you for any insight you can provide.
Glenn JocherUltralytics(đã chỉnh sửa)The raw IMX500 outputs are quantized and need post-processing. Rather than decoding them by hand, use the
pp_od_yolo_ultralyticspost-processor shown in the deployment section of the IMX500 guide.fracipriano
Hello @glenn-jocher, a code snippet would be much appreciated for double-checking. Also, I can't find the documentation you mentioned—could you link it to me, please?
Glenn JocherUltralytics(đã chỉnh sửa)The IMX500 outputs are decoded for you by the AITRIOS module library, as shown in the deployment section of the IMX500 guide:
from modlib.models.post_processors import pp_od_yolo_ultralytics def post_process(self, output_tensors): return pp_od_yolo_ultralytics(output_tensors)Let us know if this resolves the coordinate scaling issue!
fracipriano
I think there’s been a misunderstanding. I thought there were other changes to be made besides rescaling. Scaling alone cannot be the solution since (396100, 107520, 0, 0) cannot become (39, 459, 440, 177) just by a scalar multiplication.
Also, I cannot find the "What's Under the Hood?" section anywhere here https://developer.sony.com/imx500. Could you be more precise about where I should look?
Glenn JocherUltralytics(đã chỉnh sửa)The "What's Under the Hood?" section refers to our Ultralytics IMX500 documentation, not Sony's site, but it describes the quantization and conversion toolchain, not output decoding. For box decoding use the post-processor from the deployment section:
from modlib.models.post_processors import pp_od_yolo_ultralytics def post_process(self, output_tensors): return pp_od_yolo_ultralytics(output_tensors)fracipriano
Hi @glenn-jocher , thank you very much for all the support. It finally works! There was no need to rescale the boxes by 0.03125. I was missing the --bbox-normalization flag when launching the script.
Once I added the flag, everything worked fine.
Glenn JocherUltralytics(đã chỉnh sửa)Great to hear you resolved it! For the current deployment workflow, including post-processing of the model outputs, see the IMX500 deployment guide. Happy detecting with your Raspberry Pi setup! 🚀