YOLO26 모델 및 배포를 위한 MNN Export#
MNN#
MNN은 매우 효율적이고 경량인 딥러닝 프레임워크입니다. 딥러닝 모델의 추론 및 학습을 지원하며, 디바이스에서의 추론 및 학습 성능이 업계 최고 수준입니다. 현재 MNN은 Taobao, Tmall, Youku, DingTalk, Xianyu 등을 비롯한 Alibaba Inc의 30개 이상의 앱에 통합되어 있으며, 라이브 방송, 숏폼 동영상 캡처, 검색 추천, 이미지로 상품 검색, 인터랙티브 마케팅, 지분 분배, 보안 위험 관리 등 70개 이상의 사용 시나리오를 지원합니다. 또한 MNN은 IoT와 같은 임베디드 디바이스에서도 사용됩니다.
Watch: How to Export Ultralytics YOLO26 to MNN Format | Speed up Inference on Mobile Devices📱
지원되는 작업#
MNN Export는 7가지 Ultralytics 작업을 모두 지원합니다. 시맨틱 세그멘테이션과 깊이 추정은 이러한 헤드를 제공하는 유일한 제품군인 YOLO26에서만 사용할 수 있습니다.
MNN으로 Export: YOLO26 모델 변환#
Ultralytics YOLO 모델을 MNN 형식으로 변환하면 모델 호환성과 배포 유연성을 확장할 수 있습니다. 이 변환은 모바일 및 임베디드 환경에 맞게 모델을 최적화하여 리소스가 제한된 디바이스에서도 효율적인 성능을 보장합니다.
설치#
필요한 패키지를 설치하려면 다음을 실행합니다:
# Install the required package for YOLO26 and MNN
pip install ultralytics
pip install MNN사용법#
모든 Ultralytics YOLO26 모델은 기본적으로 Export를 지원하도록 설계되어 있어 선호하는 배포 워크플로에 쉽게 통합할 수 있습니다. 애플리케이션에 가장 적합한 설정을 선택하려면 지원되는 전체 Export 형식 및 구성 옵션 목록을 확인할 수 있습니다.
MNN 형식은 Export, Predict, Validate 모드를 지원합니다. 모델을 Export한 다음 Export된 모델을 로드하여 추론을 실행하거나 정확도를 검증할 수 있습니다.
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")내보내기 인수#
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
format | str | 'mnn' | 내보낸 모델의 대상 형식으로, 다양한 deployment environment와의 호환성을 정의합니다. |
imgsz | int 또는 tuple | 640 | 모델 입력에 사용할 이미지 크기입니다. 정사각형 이미지에는 정수를 사용하고, 특정 크기에는 (height, width) tuple을 사용할 수 있습니다. |
quantize | int 또는 str | None | 양자화 정밀도: 16 (FP16) 또는 8 (INT8)은 Export된 가중치를 축소합니다. 32/설정하지 않음은 FP32 가중치를 Export하지만, MNN의 CPU 런타임은 이를 FP32가 아닌 기본 low 정밀도로 계산합니다. 더 이상 사용되지 않는 half/int8 플래그를 대체합니다. |
simplify | bool | True | onnxslim을 사용하여 중간 ONNX graph를 단순화합니다. |
opset | int | None | 중간 ONNX graph의 ONNX opset 버전을 지정합니다. 설정하지 않으면 지원되는 최신 버전을 사용합니다. |
batch | int | 1 | 내보낼 모델의 배치 추론 크기 또는 predict 모드에서 내보낸 모델이 동시에 처리할 최대 이미지 수를 지정합니다. |
dynamic | bool | False | 동적 입력 이미지 크기를 활성화합니다. nms=True과 함께 사용할 수 없습니다. |
nms | bool, 선택 사항 | None | 원시 출력(None, 기본값), 임베디드 NMS(True), 또는 NMS 프리 헤드(False)를 선택합니다. 임베디드 NMS는 dynamic=False을 사용한 감지 및 포즈를 지원합니다. |
device | str | None | 내보내기에 사용할 device를 지정합니다: GPU (device=0), CPU (device=cpu), Apple silicon용 MPS (device=mps). |
내보내기 프로세스에 대한 자세한 내용은 Ultralytics 내보내기 문서 페이지를 참조하십시오.
MNN 전용 추론#
YOLO26 추론 및 전처리에 MNN만 사용하는 함수가 구현되어 있으며, 어떤 시나리오에서도 쉽게 배포할 수 있도록 Python 및 C++ 버전을 모두 제공합니다.
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)요약#
이 가이드에서는 Ultralytics YOLO26 모델을 MNN으로 Export하고 MNN을 사용하여 추론하는 방법을 소개합니다. MNN 형식은 엣지 AI 애플리케이션에서 뛰어난 성능을 제공하므로, 리소스가 제한된 디바이스에 컴퓨터 비전 모델을 배포하는 데 적합합니다.
더 자세한 사용 방법은 MNN 문서를 참조하십시오.
FAQ#
Ultralytics YOLO26 모델을 MNN 형식으로 Export하려면 다음 단계를 따르십시오:
내보내기from 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자세한 Export 옵션은 문서의 Export 페이지를 확인하십시오.
Export된 YOLO26 MNN 모델로 Predict하려면 YOLO 클래스의
predict함수를 사용하십시오.Predictionfrom 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은 다양한 플랫폼을 지원하며 활용 범위가 넓습니다:
- 모바일: Android, iOS, Harmony.
- 임베디드 시스템 및 IoT 디바이스: Raspberry Pi 및 NVIDIA Jetson과 같은 디바이스입니다.
- 데스크톱 및 서버: Linux, Windows, macOS.
YOLO26 모델을 모바일 디바이스에 배포하려면 다음을 수행하십시오:
- Android용 Build: MNN Android 가이드를 따르십시오.
- iOS용 Build: MNN iOS 가이드를 따르십시오.
- Harmony용 Build: MNN Harmony 가이드를 따르십시오.