Xuất MNN cho các model YOLO26 và triển khai#
MNN#
MNN là một framework deep learning hiệu quả cao và nhẹ. Framework này hỗ trợ suy luận và huấn luyện các model deep learning, đồng thời có hiệu năng hàng đầu trong suy luận và huấn luyện trên thiết bị. Hiện tại, MNN đã được tích hợp vào hơn 30 ứng dụng của Alibaba Inc, chẳng hạn như Taobao, Tmall, Youku, DingTalk, Xianyu, v.v., bao phủ hơn 70 kịch bản sử dụng như phát trực tiếp, quay video ngắn, đề xuất tìm kiếm, tìm kiếm sản phẩm bằng hình ảnh, marketing tương tác, phân phối quyền lợi và kiểm soát rủi ro bảo mật. Ngoài ra, MNN cũng được sử dụng trên các thiết bị nhúng, chẳng hạn như IoT.
Watch: How to Export Ultralytics YOLO26 to MNN Format | Speed up Inference on Mobile Devices📱
Các Task được hỗ trợ#
Xuất MNN hỗ trợ tất cả bảy tác vụ của Ultralytics. Phân đoạn ngữ nghĩa và ước tính độ sâu chỉ khả dụng với YOLO26, dòng model duy nhất được cung cấp các head này.
Xuất sang MNN: Chuyển đổi model YOLO26 của bạn#
Bạn có thể mở rộng khả năng tương thích của model và tính linh hoạt khi triển khai bằng cách chuyển đổi các model Ultralytics YOLO sang định dạng MNN. Việc chuyển đổi này tối ưu hóa các model cho môi trường mobile và nhúng, đảm bảo hiệu năng hiệu quả trên các thiết bị có tài nguyên hạn chế.
Cài đặt#
Để cài đặt các package bắt buộc, hãy chạy:
# Install the required package for YOLO26 and MNN
pip install ultralytics
pip install MNNCách sử dụng#
Tất cả model Ultralytics YOLO26 đều được thiết kế để hỗ trợ xuất ngay khi cài đặt, giúp dễ dàng tích hợp vào quy trình triển khai mà bạn lựa chọn. Bạn có thể xem danh sách đầy đủ các định dạng xuất và tùy chọn cấu hình được hỗ trợ để chọn thiết lập phù hợp nhất cho ứng dụng của mình.
Định dạng MNN hỗ trợ các chế độ Export, Predict và Validate. Hãy xuất model, sau đó tải model đã xuất để chạy suy luận hoặc xác thực độ chính xác.
from ultralytics import YOLO
# Load a YOLO26 model
model = YOLO("yolo26n.pt")
# Export the model to MNN format
model.export(format="mnn") # creates 'yolo26n.mnn'from ultralytics import YOLO
# Load the exported MNN model
model = YOLO("yolo26n.mnn")
# Run inference
results = model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# Load the exported MNN model
model = YOLO("yolo26n.mnn")
# Validate accuracy on the COCO8 dataset
metrics = model.val(data="coco8.yaml")Đối số Export#
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
format | str | 'mnn' | Định dạng đích của model đã export, 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 input của model. Có thể là một số nguyên đối với ảnh vuông hoặc một tuple (height, width) cho các kích thước cụ thể. |
quantize | int hoặc str | None | Độ chính xác lượng tử hóa: 16 (FP16) hoặc 8 (INT8) làm giảm trọng số đã xuất; 32/bỏ đặt sẽ xuất trọng số FP32, nhưng runtime CPU của MNN vẫn tính toán ở độ chính xác mặc định low thay vì FP32. Thay thế các cờ half/int8 đã lỗi thời. |
simplify | bool | True | Đơn giản hóa graph ONNX trung gian bằng onnxslim. |
opset | int | None | Chỉ định phiên bản opset ONNX cho graph ONNX trung gian. Nếu không thiết lập, phiên bản được hỗ trợ mới nhất sẽ được sử dụng. |
batch | int | 1 | Chỉ định batch inference size của model export hoặc số image tối đa mà model đã export sẽ xử lý đồng thời trong mode predict. |
dynamic | bool | False | Bật kích thước động cho ảnh đầu vào. Không thể kết hợp với nms=True. |
nms | bool, tùy chọn | None | Chọn đầu ra thô (None, mặc định), NMS tích hợp (True), hoặc phần đầu không có NMS (False). NMS tích hợp hỗ trợ phát hiện và ước lượng tư thế với dynamic=False. |
device | str | None | Chỉ định thiết bị dùng để export: GPU (device=0), CPU (device=cpu), MPS cho Apple silicon (device=mps). |
Để biết thêm chi tiết về quy trình export, hãy truy cập trang tài liệu Ultralytics về export.
Suy luận chỉ bằng MNN#
Một function chỉ sử dụng MNN cho suy luận và tiền xử lý YOLO26 đã được triển khai, cung cấp cả phiên bản Python và C++ để dễ dàng triển khai trong mọi kịch bản.
import argparse
import MNN
import MNN.cv as cv2
import MNN.numpy as np
def inference(model, img, precision, backend, thread):
config = {}
config["precision"] = precision
config["backend"] = backend
config["numThread"] = thread
rt = MNN.nn.create_runtime_manager((config,))
# net = MNN.nn.load_module_from_file(model, ['images'], ['output0'], runtime_manager=rt)
net = MNN.nn.load_module_from_file(model, [], [], runtime_manager=rt)
original_image = cv2.imread(img)
ih, iw, _ = original_image.shape
length = max((ih, iw))
scale = length / 640
image = np.pad(original_image, [[0, length - ih], [0, length - iw], [0, 0]], "constant")
image = cv2.resize(
image, (640, 640), 0.0, 0.0, cv2.INTER_LINEAR, -1, [0.0, 0.0, 0.0], [1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0]
)
image = image[..., ::-1] # BGR to RGB
input_var = image[None]
input_var = MNN.expr.convert(input_var, MNN.expr.NC4HW4)
output_var = net.forward(input_var)
output_var = MNN.expr.convert(output_var, MNN.expr.NCHW)
output_var = output_var.squeeze()
# output_var shape: [84, 8400]; 84 means: [cx, cy, w, h, prob * 80]
cx = output_var[0]
cy = output_var[1]
w = output_var[2]
h = output_var[3]
probs = output_var[4:]
# [cx, cy, w, h] -> [x0, y0, x1, y1]
x0 = cx - w * 0.5
y0 = cy - h * 0.5
x1 = cx + w * 0.5
y1 = cy + h * 0.5
boxes = np.stack([x0, y0, x1, y1], axis=1)
# get max prob and idx
scores = np.max(probs, 0)
class_ids = np.argmax(probs, 0)
result_ids = MNN.expr.nms(boxes, scores, 100, 0.45, 0.25)
print(result_ids.shape)
# nms result box, score, ids
result_boxes = boxes[result_ids]
result_scores = scores[result_ids]
result_class_ids = class_ids[result_ids]
for i in range(len(result_boxes)):
x0, y0, x1, y1 = result_boxes[i].read_as_tuple()
y0 = int(y0 * scale)
y1 = int(y1 * scale)
x0 = int(x0 * scale)
x1 = int(x1 * scale)
# clamp to the original image size to handle cases where padding was applied
x1 = min(iw, x1)
y1 = min(ih, y1)
print(result_class_ids[i])
cv2.rectangle(original_image, (x0, y0), (x1, y1), (0, 0, 255), 2)
cv2.imwrite("res.jpg", original_image)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, required=True, help="the yolo26 model path")
parser.add_argument("--img", type=str, required=True, help="the input image path")
parser.add_argument("--precision", type=str, default="normal", help="inference precision: normal, low, high, lowBF")
parser.add_argument(
"--backend",
type=str,
default="CPU",
help="inference backend: CPU, OPENCL, OPENGL, NN, VULKAN, METAL, TRT, CUDA, HIAI",
)
parser.add_argument("--thread", type=int, default=4, help="inference using thread: int")
args = parser.parse_args()
inference(args.model, args.img, args.precision, args.backend, args.thread)Tóm tắt#
Trong hướng dẫn này, chúng tôi giới thiệu cách xuất model Ultralytics YOLO26 sang MNN và sử dụng MNN để suy luận. Định dạng MNN mang lại hiệu năng xuất sắc cho các ứng dụng edge AI, rất phù hợp để triển khai các model computer vision trên các thiết bị có tài nguyên hạn chế.
Để biết thêm cách sử dụng, vui lòng tham khảo tài liệu MNN.
FAQ#
Để xuất model Ultralytics YOLO26 của bạn sang định dạng MNN, hãy thực hiện các bước sau:
Exportfrom ultralytics import YOLO # Load a YOLO26 model model = YOLO("yolo26n.pt") # Export to MNN format model.export(format="mnn") # creates 'yolo26n.mnn' with fp32 weight model.export(format="mnn", quantize=16) # creates 'yolo26n.mnn' with fp16 weight model.export(format="mnn", quantize=8) # creates 'yolo26n.mnn' with int8 weightĐể biết các tùy chọn xuất chi tiết, hãy xem trang Export trong tài liệu.
Để dự đoán bằng model YOLO26 MNN đã xuất, hãy sử dụng function
predicttừ class YOLO.Predictfrom ultralytics import YOLO # Load the YOLO26 MNN model model = YOLO("yolo26n.mnn") # Run inference results = model("https://ultralytics.com/images/bus.jpg") for result in results: result.show() # display to screen result.save(filename="result.jpg") # save to diskMNN linh hoạt và hỗ trợ nhiều nền tảng khác nhau:
- Mobile: Android, iOS, Harmony.
- Hệ thống nhúng và thiết bị IoT: Các thiết bị như Raspberry Pi và NVIDIA Jetson.
- Máy tính để bàn và máy chủ: Linux, Windows và macOS.
Để triển khai các model YOLO26 trên thiết bị Mobile:
- Build cho Android: Làm theo hướng dẫn MNN Android.
- Build cho iOS: Làm theo hướng dẫn MNN iOS.
- Build cho Harmony: Làm theo hướng dẫn MNN Harmony.