Ultralytics YOLO를 사용한 모델 내보내기
소개#
모델 학습의 일반적인 목표는 실제 애플리케이션에 배포하는 것입니다. Ultralytics YOLO26의 Export 모드는 학습한 모델을 다양한 형식으로 변환해 여러 플랫폼과 디바이스에서 실행할 수 있도록 합니다. 이 가이드에서는 내보내기 사용법, 인수, 지원 형식, 양자화 옵션을 다룹니다.
예정된 내보내기 지원에 대해서는 미공개 YOLO27 프리뷰를 참조하세요.
시청: 배포를 위해 다양한 형식으로 Ultralytics YOLO26 내보내기 | ONNX, TensorRT, CoreML 🚀
YOLO26의 내보내기 모드를 선택해야 하는 이유#
- 다용성: ONNX, TensorRT, CoreML 등 다양한 형식으로 내보낼 수 있습니다.
- 성능: TensorRT를 사용하면 GPU 속도를 최대 5배 높이고, ONNX 또는 OpenVINO를 사용하면 CPU 속도를 3배 높일 수 있습니다.
- 호환성: 다양한 하드웨어 및 소프트웨어 환경에 모델을 배포할 수 있습니다.
- 간편한 사용: CLI 명령 하나 또는 Python 호출 한 번으로 내보낼 수 있습니다.
사용 예시#
YOLO26n 모델을 ONNX 또는 TensorRT와 같은 다른 형식으로 내보냅니다.
from ultralytics import YOLO
# 모델 로드
model = YOLO("yolo26n.pt") # 공식 모델을 불러옵니다
model = YOLO("path/to/best.pt") # 사용자 지정 학습 모델을 불러옵니다
# 모델을 내보냅니다
model.export(format="onnx")인수#
이 표에는 YOLO 모델을 다양한 형식으로 내보낼 때 사용할 수 있는 인수가 나열되어 있습니다. 이러한 인수는 내보낸 모델의 성능, 크기, 대상 플랫폼 및 환경과의 호환성을 제어합니다.
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
format | str | 'torchscript' | 내보낸 모델의 대상 형식입니다. 'onnx', 'torchscript', 'engine'(TensorRT) 등이 있습니다. 형식마다 서로 다른 배포 환경과의 호환성을 제공합니다. |
name | str | None | 지원이 필요한 형식의 하드웨어 타깃 이름: Hailo 아키텍처('hailo8', 'hailo8l', 'hailo10h', 'hailo15h', 'hailo15l'; 기본값은 'hailo8l'), Rockchip RKNN 칩(기본값은 'rk3588'), Huawei Ascend SoC(CANN --soc_version; 기본값은 'Ascend310B4'), Qualcomm QNN HTP 타깃(기본값은 '73'), 또는 AMD Xilinx Versal AI Edge Series Gen 2 디바이스(기본값은 've2-xc2ve3858', VEK385 평가 키트)입니다. 다른 모드에서 사용하는 project/name 실행 이름 쌍과는 별개입니다. |
imgsz | int 또는 tuple | 640 | 모델 입력에 사용할 이미지 크기입니다. 정사각형 이미지의 경우 정수(예: 640으로 640×640)를 지정하거나, 특정 크기를 지정하려면 튜플 (height, width)을 지정할 수 있습니다. 값을 전달하지 않으면 내보내기 시 로드된 체크포인트에 기록된 학습 크기를 사용합니다. 공식 YOLO26 체크포인트에는 Cityscapes(yolo26n-sem.pt)로 사전 학습된 semantic 모델의 경우 1024, depth의 경우 768, classify의 경우 224, OBB의 경우 1024, Cityscapes로 사전 학습된 semantic 모델(yolo26n-sem-ade20k.pt)을 포함한 그 외 작업의 경우 640이 기록되어 있으며, fine-tune 모델에는 학습에 사용한 imgsz가 기록됩니다. YAML에서 빌드한 모델에는 기록된 학습 크기가 없으므로 640을 사용합니다. |
optimize | bool | False | DEEPX의 컴파일러 최적화 수준을 높여 컴파일 시간을 늘리는 대신 추론 지연 시간을 줄입니다. |
quantize | int 또는 str | None | 양자화 정밀도: 16 (FP16, 모델 크기를 줄이고 지원되는 하드웨어에서 추론 속도를 높일 수 있음) 또는 8 (INT8/PTQ, 모델을 추가로 압축하면서 정확도 손실을 최소화하며, 주로 엣지 디바이스에 사용됨; 보정 data/fraction 필요); 32은 지원되는 경우 FP32를 선택합니다. 설정하지 않으면 NXP용 INT8처럼 대상에서 양자화를 요구하지 않는 한 FP32를 사용합니다. quantize=8로 학습된 체크포인트는 항상 INT8로 내보냅니다. onnx 및 engine는 보정 없이 체크포인트에 포함된 범위에서 내보내며, 다른 형식이나 정밀도는 거부됩니다. 'w8a8' 및 'w16a16'은 8 및 16의 별칭입니다. 혼합 정밀도인 'w8a16' (16비트 활성화를 사용하는 INT8 가중치: CoreML, LiteRT, QNN)와 'w8a32' (동적 INT8: LiteRT)는 해당 형식에서만 허용됩니다. 사용 중단된 half/int8 플래그를 대체합니다 (half=True → 16, int8=True → 8. 사용 중단 경고와 함께 계속 허용됩니다). 대상 형식에서 지원하는 정밀도만 사용할 수 있습니다(아래 참조). |
dynamic | bool | False | TorchScript, ONNX, OpenVINO, TensorRT, CoreML 및 MNN 내보내기에서 동적 입력 크기를 허용하여 다양한 이미지 크기를 유연하게 처리할 수 있습니다. |
simplify | bool | True | 내보내기 형식을 참고하세요. ONNX 그래프를 생성하는 내보내기의 중간 ONNX 그래프를 onnxslim으로 단순화하여 추론 엔진의 성능과 호환성을 높일 수 있습니다. |
opset | int | None | 서로 다른 ONNX 파서 및 런타임과의 호환성을 위해 ONNX 그래프를 생성하는 내보내기의 ONNX opset 버전을 지정합니다(내보내기 형식 참조). 설정하지 않으면 opset 18를 사용하며(PyTorch < 2.4에서는 더 낮은 버전), 설치된 onnx 버전으로 제한됩니다. RKNN, Ascend, AMD Xilinx, Hailo 및 RT-DETR TensorFlow 내보내기는 자체 opset을 설정합니다. |
workspace | float 또는 None | None | 메모리 사용량과 성능의 균형을 맞추기 위해 TensorRT 최적화에 사용할 최대 워크스페이스 크기를 GiB 단위로 설정합니다. 장치의 최대값까지 TensorRT가 자동으로 할당하도록 하려면 None을 사용하세요. |
nms | bool, 선택 사항 | None | None은 외부 NMS를 위해 원시 일대다 예측을 내보냅니다(YOLO26은 Axelera에서 NMS가 필요 없는 헤드를 유지합니다). True는 지원되는 경우 NMS를 포함하고, False은 사용 가능한 경우 NMS가 필요 없는 헤드를 선택합니다. CoreML에 포함된 NMS는 정적 형식의 detect, segment, pose를 지원합니다. End-to-End Detection 가이드를 참조하세요. |
conf | float | None | 내보내기 시 NMS를 생성하는 다음 항목에서 사용하는 신뢰도 임계값입니다. nms=True 내보내기, Hailo의 비엔드투엔드 detect 내보내기, 내부적으로 nms=True을 강제하는 IMX의 detect, pose 및 segment 내보내기입니다. 설정하지 않은 경우 기본값은 0.25입니다. |
iou | float | 0.5 | 내보내기 시 NMS를 생성하는 다음 항목에서 사용하는 IoU 임계값입니다. nms=True 내보내기, Hailo의 비엔드투엔드 detect 내보내기, 내부적으로 nms=True를 강제하는 IMX의 detect, pose 및 segment 내보내기입니다. |
max_det | int | 300 | 내보낸 모델 출력에서 유지할 최대 감지 수입니다. CoreML 감지의 기본 NMS 파이프라인에는 감지 수 제한이 없으므로 이를 제외한 모든 형식의 nms=True 내보내기에 적용됩니다. 또한 NMS가 없는 엔드투엔드 감지 내보내기(YOLO26, YOLOv10, 사용 가능한 앵커 수로 제한됨)와 IMX의 detect, pose 및 segment 내보내기에도 적용됩니다. |
agnostic_nms | bool | False | 표준 nms=True 파이프라인을 통해 내보내기 시 NMS를 생성하는 모든 경우에 클래스 구분 없는 NMS를 활성화합니다. 여기에는 CoreML 자체 NMS 단계도 포함되며, 같은 클래스 내에서만 억제하는 대신 서로 다른 클래스에 걸친 겹치는 상자 중 점수가 낮은 상자를 억제합니다. 자체 NMS 구성을 생성하는 Hailo 또는 IMX에는 적용되지 않습니다. 해당 구성에는 클래스 구분 옵션이 없으므로 이 플래그와 관계없이 클래스 구분을 유지합니다. NMS가 없는 엔드투엔드 내보내기(YOLO26, YOLOv10)에도 적용됩니다. 이 경우 IoU 임계값에 따른 서로 다른 상자 간 억제가 아니라 동일한 감지가 여러 클래스 레이블로 나타나는 것(IoU=1.0 중복)만 방지합니다. |
batch | int | 1 | predict 모드에서 내보낸 모델이 동시에 처리할 이미지 수의 최댓값 또는 내보낸 모델의 배치 추론 크기를 지정합니다. 내보내기 인수에 batch이 없는 형식은 배치 크기 1로 내보내며 다른 값은 허용하지 않습니다. |
device | str | None | 내보내기에 사용할 장치를 지정합니다. GPU(device=0), CPU(device=cpu), Apple 실리콘용 MPS(device=mps), Huawei Ascend NPU(device=npu 또는 device=npu:0), NVIDIA Jetson용 DLA(device=dla:0 또는 device=dla:1) 중에서 선택합니다. TensorRT 내보내기는 GPU를 자동으로 사용하지만, TensorRT 11은 DLA를 지원하지 않습니다. device=npu을 사용하는 OpenVINO INT8 내보내기는 Intel NPU에 맞게 최적화됩니다. |
verbose | bool | False | format='engine' 내보내기 중 TensorRT 빌더 로그의 심각도 수준을 VERBOSE로 높입니다. 다른 내보내기 형식에서는 무시됩니다. |
data | str | None | 캘리브레이션 데이터셋: YAML 경로(분류 작업이 아닌 경우), NDJSON 경로 또는 URL, Platform 데이터셋 URI(ul://owner/datasets/name) 또는 웹 URL입니다. Platform 데이터셋을 사용하려면 API 키와 Python 3.11 이상이 필요합니다. 분류 작업에서는 데이터셋 디렉터리 또는 기본 제공 데이터셋 이름도 사용할 수 있습니다. INT8이 활성화된 상태에서 지정하지 않으면, Ultralytics는 필요한 경우 작업별 캘리브레이션 데이터셋을 선택하거나 모델 작업의 기본 데이터셋을 사용합니다. quantize=8로 학습한 체크포인트에는 자체 INT8 범위가 포함되어 있어 캘리브레이션 데이터가 필요하지 않습니다. |
split | str | 'val' | data에서 INT8 양자화 보정 데이터 로더를 생성할 때 사용할 데이터셋 분할('train', 'val' 또는 'test')입니다. |
fraction | float, int 또는 list | 1.0 | INT8 보정에 사용할 데이터셋 하위 집합입니다. 비율, 이미지 수 또는 [train, val, test] 값을 지정할 수 있습니다. 1은 전체 분할을 의미하고, 1보다 큰 정수는 이미지 수를 의미합니다. 선택적 test 항목에서만 0/0.0를 지정해 없음을 나타낼 수 있습니다. 두 항목으로 이루어진 목록에서는 test가 전체로 유지됩니다. |
모델 크기, 속도, 정확도 사이에서 최적의 균형을 얻으려면 배포 환경, 하드웨어 제약, 성능 목표에 맞는 형식과 설정을 선택하세요.
내보내기 형식#
사용 가능한 YOLO26 내보내기 형식은 아래 표에 나와 있습니다. format 인수를 사용해 원하는 형식으로 내보낼 수 있습니다(예: format='onnx' 또는 format='engine'). 내보낸 모델에서 바로 예측을 실행하거나 검증할 수도 있습니다(예: yolo predict model=yolo26n.onnx). 내보내기가 완료되면 해당 모델의 사용 예제가 표시됩니다. 로컬 환경을 설정하지 않고 Ultralytics Platform 브라우저에서 바로 모델을 내보낼 수도 있습니다.
| 형식 | format 인수 | 모델 | 메타데이터 | 인수 |
|---|---|---|---|---|
| PyTorch | - | yolo26n.pt | ✅ | - |
| TorchScript | torchscript | yolo26n.torchscript | ✅ | imgsz, quantize, dynamic, nms, batch, device |
| ONNX | onnx | yolo26n.onnx | ✅ | imgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device |
| OpenVINO | openvino | yolo26n_openvino_model/ | ✅ | imgsz, quantize, dynamic, nms, batch, data, fraction, device |
| TensorRT | engine | yolo26n.engine | ✅ | imgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device |
| CoreML | coreml | yolo26n.mlpackage | ✅ | imgsz, dynamic, quantize, nms, batch, device |
| Apple Core AI | coreai | yolo26n.aimodel | ✅ | imgsz, batch, quantize |
| TF SavedModel | saved_model | yolo26n_saved_model/ | ✅ | imgsz, quantize, opset, nms, batch, data, fraction, device |
| TF GraphDef | pb | yolo26n.pb | ❌ | imgsz, opset, batch, device |
| TF Edge TPU | edgetpu | yolo26n_edgetpu.tflite | ✅ | imgsz, quantize, opset, data, fraction, device |
| LiteRT | litert | yolo26n.tflite | ✅ | imgsz, quantize, batch, data, fraction, device |
| PaddlePaddle | paddle | yolo26n_paddle_model/ | ✅ | imgsz, batch, device |
| MNN | mnn | yolo26n.mnn | ✅ | imgsz, batch, dynamic, quantize, simplify, opset, nms, device |
| NCNN | ncnn | yolo26n_ncnn_model/ | ✅ | imgsz, quantize, device |
| IMX500 | imx | yolo11n_imx_model/ | ✅ | imgsz, quantize, data, fraction, nms, device |
| RKNN | rknn | yolo26n_rknn_model/ | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| ExecuTorch | executorch | yolo26n_executorch_model/ | ✅ | imgsz, quantize, batch, data, fraction, device |
| Axelera | axelera | yolo26n_axelera_model/ | ✅ | imgsz, batch, quantize, data, fraction, device |
| DEEPX | deepx | yolo26n_deepx_model/ | ✅ | imgsz, quantize, simplify, opset, data, optimize, device |
| Qualcomm QNN | qnn | yolo26n_qnn.onnx | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| Hailo | hailo | yolo26n_hailo_model/ | ✅ | imgsz, name, quantize, data, fraction, simplify, conf, iou, device |
| Huawei Ascend | ascend | yolo26n_ascend_model/ | ✅ | imgsz, batch, name, quantize, opset, simplify, nms, device |
| AMD Xilinx | xilinx | yolo26n_xilinx_model/ | ✅ | imgsz, name, quantize, data, fraction, opset, simplify, device |
| NXP | nxp | yolo26n_nxp.tflite | ✅ | imgsz, quantize, data, fraction, device |
| ST Edge AI | stedgeai | yolo26n_stedgeai.onnx | ✅ | imgsz, quantize, data, fraction, opset, simplify, device |
nms=None은 외부 NMS를 위해 기본적으로 원시 출력을 사용합니다(YOLO26은 Axelera에서 NMS가 필요 없는 헤드를 유지합니다). 사용 가능한 NMS가 필요 없는 헤드를 선택하려면 nms=False를 설정하세요. 지원되지 않는 형식은 해당 형식의 기본 출력 경로로 대체됩니다. 위의 nms 항목은 nms=True로 NMS를 포함할 수 있는 형식을 나타냅니다.
대부분의 형식에는 ultralytics과 함께 설치되지 않는 패키지가 필요합니다. 필요한 패키지가 없으면 내보내기 과정에서 런타임에 uv 또는 pip를 사용해 설치하며, Linux에서는 IMX용 Java와 같은 시스템 패키지를 위해 apt도 사용합니다. Edge TPU 컴파일러는 apt 또는 sudo 없이 다운로드됩니다. 예를 들어 컨테이너 이미지, CI 작업, 프로덕션 서비스에서 환경을 변경되지 않도록 유지하려면 YOLO_AUTOINSTALL=False을 설정하세요. 그러면 내보내기 과정에서 누락된 패키지를 계속 확인하고 보고하지만 환경은 변경하지 않으며, 패키지가 설치될 때까지 실패합니다.
export YOLO_AUTOINSTALL=False양자화 옵션#
내보내기 정밀도를 지정하려면 quantize 인수를 사용합니다. 문자열 값은 대소문자를 구분하지 않으며, Ultralytics는 내보내기 전에 허용된 별칭을 표준 형식으로 변환합니다:
| 요청 값 | 표준 값 | 의미 |
|---|---|---|
8, "8", "int8", "w8a8" | 8 | INT8 가중치 및 활성화값 |
16, "16", "fp16", "w16a16" | 16 | FP16 가중치 및 활성화값 |
32, "32", "fp32", "w32a32" | 32 | FP32로 내보내며, 설정하지 않은 경우와 동일합니다. 단, CoreML NMS ML Programs는 기본적으로 FP16을 사용합니다. |
"w8a16" | "w8a16" | INT8 가중치와 16비트 활성화값(FP16, LiteRT에서는 INT16) |
"w8a32" | "w8a32" | INT8 가중치와 FP32 활성화값(LiteRT 동적 INT8, 보정 불필요) |
기존 half=True 및 int8=True 플래그는 지원 중단 경고와 함께 계속 허용되며, 각각 quantize=16 및 quantize=8으로 전달됩니다.
모든 내보내기 형식이 모든 정밀도를 지원하는 것은 아닙니다. 명시적인 quantize 요청은 해당 정밀도로 내보내거나 내보내기 전에 실패합니다:
| 형식 | FP32 (32/미설정) | FP16 (16) | INT8 (8) | W8A16 ("w8a16") | 참고 |
|---|---|---|---|---|---|
| PyTorch | ✅ | 해당 없음 | 해당 없음 | 해당 없음 | 기본 학습/체크포인트 형식입니다. |
| TorchScript | ✅ | ✅ GPU 전용 | ❌ | ❌ | FP16 TorchScript 내보내기에는 device=0이 필요하며, CPU 내보내기는 FP32입니다. |
| ONNX | ✅ | ✅ | ✅ | ❌ | INT8은 ONNX Runtime 정적 양자화와 보정 데이터를 사용합니다. |
| OpenVINO | ✅ | ✅ | ✅ | ❌ | INT8은 NNCF 학습 후 양자화를 사용합니다. |
| TensorRT | ✅ | ✅ | ✅ | ❌ | INT8에는 대표성 있는 보정 데이터가 필요합니다. |
| CoreML | ✅¹ | ✅ | ✅ | ✅ | CoreML INT8은 가중치 양자화이며, W8A16은 INT8 가중치와 FP16 활성화값을 사용합니다. ¹NMS ML Programs를 설정하지 않으면 기본값은 FP16이며, 세그먼트/포즈 nms=True 내보내기는 항상 FP16입니다. |
| Core AI | ✅ | ✅ | ❌ | ❌ | 기본값은 FP32이며, quantize=16을 사용하면 .aimodel FP16 에셋을 사용할 수 있습니다. INT8 경로는 없습니다. |
| TF SavedModel | ✅ | ❌ | ✅ | ❌ | INT8 파일은 FP32 SavedModel과 같은 위치의 .tflite에 생성됩니다. |
| TF GraphDef | ✅ | ❌ | ❌ | ❌ | 내보내기 시 정밀도 변환을 수행하지 않습니다. |
| Edge TPU | ❌ | ❌ | ✅ 자동 | ❌ | Edge TPU에는 INT8이 필요하며, 설정하지 않으면 자동으로 활성화됩니다. |
| LiteRT | ✅ | ❌ | ✅ | ✅ | 정적 INT8(8)과 "w8a16"(int8 가중치 + int16 활성화값)은 보정 데이터를 사용합니다. 또한 "w8a32" 동적 INT8도 지원하며, 보정이 필요하지 않습니다. quantize=16은 별도의 내보내기 형식이 아닙니다. FP32 모델은 GPU delegate를 통해 런타임에 FP16으로 실행됩니다. |
| PaddlePaddle | ✅ | ❌ | ❌ | ❌ | 내보내기 시 정밀도 변환을 수행하지 않습니다. |
| MNN | ✅ | ✅ | ✅ | ❌ | INT8은 MNN 변환을 통한 가중치 양자화입니다. |
| NCNN | ✅ | ✅ | ❌ | ❌ | 모바일/임베디드 런타임 형식입니다. |
| IMX500 | ❌ | ❌ | ✅ 자동 | ❌ | IMX500에는 양자화가 필요하며, 설정하지 않으면 INT8이 자동으로 활성화됩니다. |
| RKNN | ❌ | ✅ 칩에 따라 다름 | ✅ | ❌ | RK3588/RK3576/RK3566/RK3568/RK3562/RK2118/RV1126B는 FP16 또는 INT8을 지원하며, RV1103/RV1106 변형은 INT8만 지원합니다. |
| ExecuTorch | ✅ | ❌ | ✅ | ❌ | 정적 INT8(8)은 보정 데이터를 사용하며 detect, segment, pose 및 OBB 헤드를 FP32로 유지합니다. |
| Axelera | ❌ | ❌ | ✅ 자동 | ❌ | Axelera 내보내기에는 INT8이 필요하며, 설정하지 않으면 자동으로 활성화됩니다. |
| DEEPX | ❌ | ❌ | ✅ 자동 | ❌ | DEEPX 내보내기에는 INT8이 필요하며, 설정하지 않으면 자동으로 활성화됩니다. |
| Qualcomm QNN | ❌ | ❌ | ❌ | ✅ 자동 | QNN HTP 내보내기는 16비트 활성화값을 사용하는 INT8 가중치로 고정됩니다. |
| Hailo | ❌ | ❌ | ✅ 자동 | ❌ | Hailo 내보내기에는 INT8이 필요하며, 설정하지 않으면 자동으로 활성화됩니다. |
| Huawei Ascend | ❌ | ✅ 자동 | ❌ | ❌ | Ascend AI Core 컨볼루션은 FP16/INT8 입력만 허용하므로 ATC는 FP16으로 컴파일합니다. 설정하지 않으면 자동으로 활성화됩니다. |
| AMD Xilinx | ❌ | ❌ | ✅ 자동 | ❌ | AMD Xilinx 내보내기에는 Vitis AI INT8(VINT8)이 필요하며, 설정되지 않은 경우 자동으로 활성화됩니다. |
| NXP | ❌ | ❌ | ✅ 자동 | ❌ | NXP i.MX95를 내보내려면 Neutron SDK 3.3.0과 함께 INT8이 필요합니다. 설정되지 않은 경우 자동으로 활성화됩니다. |
| ST Edge AI | ✅ | ❌ | ✅ | ❌ | INT8는 ONNX Runtime QDQ 형식으로 전체 그래프를 양자화합니다. 박스와 키포인트 출력은 [0, 1]으로 정규화되므로 헤드도 양자화됩니다. |
INT8 및 W8A16 내보내기의 경우, 대상 통합에서 기본값 또는 자동 활성화 동작을 문서화하지 않은 한 data을 사용해 대표성 있는 보정 데이터를 제공하세요(예: data="coco8.yaml"). LiteRT "w8a32"(동적 INT8) 방식에는 보정 데이터가 필요하지 않습니다.
양자화 인식 학습#
위의 INT8 내보내기는 학습 후 양자화(PTQ) 방식이며, data에 대한 단일 보정 과정에서 범위를 관찰합니다. 반면 양자화 인식 학습(QAT)은 가짜 양자화를 학습 과정에 포함해 INT8을 견딜 수 있는 가중치를 학습하므로, 보정만으로 손실되는 정확도를 회복합니다. 사전 학습된 체크포인트를 미세 조정하려면 train에 quantize=8을 전달한 다음 평소처럼 내보내세요.
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.train(
data="coco.yaml",
quantize=8,
epochs=5,
batch=64,
optimizer="AdamW",
lr0=0.00001,
lrf=0.1,
warmup_epochs=0.5,
cos_lr=True,
mosaic=0.0,
)
model.export(format="engine", quantize=8) # 범위는 체크포인트에 포함되므로 보정 데이터가 필요하지 않습니다사전 학습된 체크포인트를 미세 조정할 때는 학습률을 낮게 설정하세요. QAT는 처음에 정확도를 낮출 수 있으며, 학습 후 양자화 대비 효과는 모델, 데이터셋, 학습 예산에 따라 달라집니다. 내보낸 모델을 원본 체크포인트 및 학습 후 양자화된 내보내기 결과와 모두 비교해 검증하세요. 학습 중 가짜 양자화로 측정한 점수만으로는 배포 정확도를 확인할 수 없습니다.
QAT의 효과는 내보내기 백엔드 자체의 보정이 모델을 얼마나 잘 처리하는지에 따라 달라집니다. 아래 값은 COCO val2017에서 TensorRT 10.16 엔진을 imgsz=640 및 배치 크기 1로 측정한 mAP50-95이며, 각 QAT 체크포인트는 epochs=20 patience=3으로 학습되었습니다:
| 모델 | FP32 엔진 | PTQ INT8 엔진 | QAT INT8 엔진 |
|---|---|---|---|
yolo26n | 0.4032 | 0.3934 | 0.3935 |
yolo26s | 0.4794 | 0.4412 | 0.4711 |
yolo26m | 0.5269 | 0.4696 | 0.5137 |
yolo26l | 0.5440 | 0.4889 | 0.5307 |
yolo26x | 0.5701 | 0.5138 | 0.5527 |
전체 범위에서 QAT는 FP32 대비 mAP50-95를 0.008~0.017 낮추는 반면, 학습 후 양자화는 yolo26n에서 0.010, 더 큰 모델에서 0.038~0.057의 손실을 초래합니다. 따라서 보정이 이미 잘 작동하는 가장 작은 모델에서는 QAT의 이점이 거의 없으며, 나머지 모델에서는 0.030~0.044의 이점을 제공합니다. 다른 데이터셋, 내보내기 형식 또는 TensorRT 버전에서는 수치가 달라질 수 있으므로 직접 측정하세요.
QAT 모델에는 compile=False이 필요합니다. ModelOpt의 양자화 모듈은 torch.compile을 지원하지 않습니다.
헤드의 출력 레이어 중 Conv 블록 외부에 있는 일반 컨볼루션 및 선형 레이어는 INT8 정확도 손실을 줄이기 위해 의도적으로 float로 유지되며, TensorRT는 양자화되지 않은 레이어에 FP16 혼합 정밀도를 적용합니다. QAT는 NVIDIA TensorRT Model Optimizer를 통해 실행되며, 이 도구는 처음 사용할 때 자동으로 설치되고, 결과 체크포인트를 로드하려면 이 도구가 설치되어 있어야 합니다. 이러한 범위 정보는 체크포인트와 함께 저장되며 onnx 및 engine 내보내기에서는 이를 Q/DQ 노드로 출력하지만, 다른 형식은 대신 캘리브레이션 정보를 사용하고 QAT 체크포인트를 거부합니다.
다음 단계#
내보낸 모델의 실행 방법은 배포 대상의 통합 가이드를 참조하세요. ONNX, TensorRT, CoreML 등의 가이드는 전체 통합 목록에서 확인할 수 있습니다.
자주 묻는 질문#
Python API 또는 CLI를 사용해 YOLO26 모델을 ONNX로 내보내세요.
예제from ultralytics import YOLO # 모델 로드 model = YOLO("yolo26n.pt") # 공식 모델을 불러옵니다 model = YOLO("path/to/best.pt") # 사용자 지정 학습 모델을 불러옵니다 # 모델을 내보냅니다 model.export(format="onnx")다양한 입력 크기 처리와 같은 고급 옵션을 포함해 자세한 절차를 알아보려면 ONNX 통합 가이드를 참조하세요.
모델 내보내기에 TensorRT를 사용하면 NVIDIA GPU에서 성능을 크게 향상할 수 있습니다. TensorRT로 내보낸 YOLO26 모델은 GPU 속도를 최대 5배까지 높일 수 있어 실시간 추론 애플리케이션에 적합합니다.
- 다용도성: 특정 하드웨어 구성에 맞게 모델을 최적화합니다.
- 속도: 고급 최적화를 통해 추론 속도를 높입니다.
- 호환성: NVIDIA 하드웨어와 원활하게 통합됩니다.
TensorRT 통합에 대한 자세한 내용은 TensorRT 통합 가이드를 참조하세요.
INT8 양자화는 모델을 압축하고 추론 속도를 높이며, 특히 엣지 디바이스에서 효과적입니다.
quantize=8으로 활성화하세요.예제from ultralytics import YOLO model = YOLO("yolo26n.pt") # 모델 로드 model.export(format="onnx", quantize=8, data="coco8.yaml")INT8 양자화는 ONNX, TensorRT, OpenVINO, CoreML, Rockchip RKNN, AMD Xilinx와 같은 형식에 적용할 수 있습니다. 최적의 양자화 결과를 얻으려면
data매개변수를 사용해 대표성을 갖춘 데이터셋을 제공하세요. 허용되는quantize값과 지원 형식은 양자화 옵션을 참조하세요.동적 입력 크기를 사용하면 내보낸 모델이 다양한 이미지 크기를 처리할 수 있어 유연성이 향상되고 사용 사례별 처리 효율성이 최적화됩니다. ONNX나 TensorRT와 같은 형식으로 내보낼 때 동적 입력 크기를 활성화하면 모델이 다양한 입력 형태를 받을 수 있습니다.
이 기능을 활성화하려면 내보내기 중
dynamic=True플래그를 사용하세요:예제from ultralytics import YOLO model = YOLO("yolo26n.pt") model.export(format="onnx", dynamic=True)동적 입력 크기 설정은 비디오 처리나 다양한 소스의 이미지 처리처럼 입력 크기가 달라질 수 있는 애플리케이션에서 특히 유용합니다.
YOLO()을 사용해 로드한 동적 내보내기는 내보내기 시점의imgsz(정사각형이 아닌 내보내기의 긴 변)에서 예측 및 검증을 수행하는 반면, PyTorch 모델은 학습 시imgsz를 사용합니다. 다른 크기로 실행하려면imgsz을 전달합니다.PyTorch 모델과 동적 내보내기는 기본적으로 최소 직사각형 패딩을 사용하지만, 정적 내보내기는 전체
imgsz크기로 패딩하므로 신뢰도 임계값에 가까운 감지 결과가 달라질 수 있습니다. 정적 내보내기와 일치시키려면 네이티브 추론에rect=False를 사용하거나, 지원되는 경우dynamic=True을 사용해 내보내세요.다음 내보내기 인수는 모델 성능에 가장 큰 영향을 줍니다.
format:내보낸 모델의 대상 형식입니다(예:onnx,torchscript,saved_model).imgsz:모델 입력에 사용할 이미지 크기입니다(예:640또는(height, width)).quantize:양자화 정밀도입니다. 예를 들어8/"int8",16/"fp16",32/"fp32"또는 지원 형식에서 사용하는 혼합 가중치/활성화 방식인"w8a16"및"w8a32"(LiteRT 동적 INT8)이 있습니다. 양자화 옵션을 참조하세요.dynamic:ONNX, OpenVINO, TensorRT처럼 동적 형태를 지원하는 형식에서 가변 입력 크기를 허용합니다.nms:은 외부 NMS를 위한 원시 출력(None; YOLO26은 Axelera에서 NMS가 필요 없는 헤드를 유지합니다), 포함된 NMS(True) 또는 NMS가 필요 없는 헤드(False)를 선택합니다.device:내보내기 중 모델 추적에 사용할 디바이스입니다. 예를 들어 첫 번째 CUDA GPU에는cpu또는0를 사용합니다. FP16 TorchScript에는 GPU가 필요합니다.
특정 하드웨어 플랫폼에 배포할 때는 NVIDIA GPU용 TensorRT, Apple 디바이스용 CoreML, Google Coral 디바이스용 Edge TPU와 같은 특화된 내보내기 형식을 고려하세요.
YOLO 모델을 ONNX 또는 TensorRT와 같은 형식으로 내보내면 출력 텐서 구조는 모델 작업에 따라 달라집니다. 이러한 출력을 이해하는 것은 사용자 지정 추론 구현에 중요합니다.
nms=False을 사용해 내보낸 YOLO26 detection models(예:yolo26n.pt)의 경우, 지원되는 형식은[x1, y1, x2, y2, confidence, class_id]개의 값을 포함하는(batch_size, max_detections, 6)형태의 NMS가 필요 없는 출력을 생성합니다. 기본max_det=300를 사용하면 일반적으로(batch_size, 300, 6)형태입니다. 일부 제약이 있는 형식은 엔드투엔드 연산자를 지원하지 않을 경우 자동으로 기존 출력 레이아웃으로 대체됩니다.기본적으로(
nms=None), YOLO26을 포함한 detection 모델은 원시 일대다 예측을 내보냅니다(YOLO26은 Axelera에서 NMS가 필요 없는 헤드를 유지합니다). 출력은 일반적으로(batch_size, 4 + num_classes, num_predictions)와 같은 형태의 단일 텐서이며, 채널은 박스 좌표와 클래스별 점수를 나타냅니다.num_predictions은 내보내기 입력 해상도에 따라 달라지며 동적일 수 있습니다. End-to-End Detection 가이드에서 종단 간 출력을 유지하는 형식을 확인할 수 있습니다.segmentation 모델(예:
yolo26n-seg.pt)은 일반적으로 두 개의 출력을 생성합니다. 첫 번째 텐서는(batch_size, 4 + num_classes + mask_dim, num_predictions)형태(박스, 클래스 점수, 마스크 계수)이고, 두 번째 텐서는(batch_size, mask_dim, proto_h, proto_w)형태이며 계수와 함께 인스턴스 마스크를 생성하는 데 사용되는 마스크 프로토타입을 포함합니다. 크기는 내보내기 입력 해상도에 따라 달라집니다(동적일 수 있음).pose 모델(예:
yolo26n-pose.pt)의 출력 텐서는 일반적으로(batch_size, 4 + num_classes + keypoint_dims, num_predictions)형태입니다. 여기서keypoint_dims는 pose 사양(예: 키포인트 수와 신뢰도 포함 여부)에 따라 달라지고,num_predictions은 내보내기 입력 해상도에 따라 달라집니다(동적일 수 있음).ONNX 추론 예제에서는 각 모델 유형의 출력을 처리하는 방법을 보여줍니다.
Ultralytics는 현재 YOLO 모델 전용 C++ 추론 API를 제공하지 않습니다. C++ 배포의 경우 모델을 ONNX, TensorRT, TorchScript 또는 MNN과 같은 런타임 형식으로 내보낸 다음, 내보낸 아티팩트를 해당 런타임의 네이티브 C++ API로 로드하세요.
예를 들어
yolo export model=yolo26n.pt format=onnx으로 detection 모델을 내보내고.onnx파일을 ONNX Runtime C++로 실행하거나,format=engine로 내보내고 TensorRT C++ 애플리케이션에서 TensorRT 엔진을 실행할 수 있습니다. 사용자 지정 C++ 후처리를 사용할 때는 작업 및 내보내기 설정에 맞는 출력 텐서 레이아웃을 사용하세요. 기본 YOLO26 detection 내보내기는 외부 NMS가 필요한 원시 예측 텐서를 반환합니다. NMS가 필요 없는 detection을(batch, max_det, 6)형태로 내보내려면nms=False을 사용하거나, 지원되는 형식에서 NMS를 포함하려면nms=True를 사용하세요.quantize=16(FP16) 또는quantize=8(INT8)로 내보내면 모델 크기를 줄이고 성능을 개선하기 위해 대부분의 텐서가 낮은 정밀도로 변환됩니다. 하지만nms=False가 활성화되면 클래스 인덱스를 포함한 후처리가 내보낸 그래프에 직접 포함됩니다.output0텐서에는 클래스 인덱스가 포함되며, 내부적으로 부동 소수점 값으로 표현됩니다. FP16은 가수부 정밀도가 제한되어 있어 2048보다 큰 정수 값을 안정적으로 표현할 수 없습니다. 잠재적인 정밀도 손실이나 잘못된 클래스 ID를 방지하기 위해output0은 의도적으로 FP32로 유지됩니다.전체 FP16 출력이 필요한 경우 GPU에서
nms=None으로 내보내고 후처리를 외부에서 수행하세요. CPU에서 내보낸 FP16 ONNX는 내부 그래프만 변환하며 입력과 출력은 계속 FP32로 유지됩니다.
댓글447
질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.
yubaobao-GPU
你好,请问为什么我转onnx的时候会显示end2end参数非法 (ywh_26) root@ai-avcon:/data/ywh_folder/yolo/yolo26# python to_onnx.py WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem with your settings or a recent ultralytics package update. View Ultralytics Settings with 'yolo settings' or at '/root/.config/Ultralytics/settings.json' Update Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings. Traceback (most recent call last): File "/data/ywh_folder/yolo/yolo26/to_onnx.py", line 12, in model.export( File "/data/ywh_folder/yolo/yolo26/ultralytics/engine/model.py", line 710, in export return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model) File "/data/ywh_folder/yolo/yolo26/ultralytics/engine/exporter.py", line 312, in init self.args = get_cfg(cfg, overrides) File "/data/ywh_folder/yolo/yolo26/ultralytics/cfg/init.py", line 308, in get_cfg check_dict_alignment(cfg, overrides) File "/data/ywh_folder/yolo/yolo26/ultralytics/cfg/init.py", line 505, in check_dict_alignment raise SyntaxError(string + CLI_HELP_MSG) from e SyntaxError: 'end2end' is not a valid YOLO argument.
我是用的8.4.6版本的ultralytics
1
Glenn JocherUltralyticsultralytics==8.4.6还不支持end2end这个导出参数(它是给支持 NMS-free 的新模型/新版本用的),所以你这边要么把model.export()里的end2end=...去掉,要么升级到最新 Ultralytics;另外你的报错路径显示实际导入的是本地仓库.../yolo26/ultralytics,建议先跑一次yolo checks并把文本输出贴上来确认是否存在多套安装/路径冲突(参数列表可参考 Model.export() 参考文档)。pip install -U ultralytics yolo checks
qcname
您好,使用.pt和导出为.onnx进行yolov8模型的图片中目标检测时,参数设置一致,但是最终检测框数量,位置不完全一致。比如.onnx比.pt多画一个或者检测到.pt检测不出来的类别,请问是什么问题导致的呢?
1
Paula DerrengerUltralytics@nacenace 您好,
感谢您提出这个问题!在导出模型时遇到检测结果不一致的情况确实令人困惑。以下是一些可能的原因和解决方法:
-
版本一致性:请确保您使用的是最新版本的
torch和ultralytics。您可以通过以下命令进行升级:pip install --upgrade torch ultralytics -
模型导出参数:导出为 ONNX 时,某些参数可能会影响模型的行为。请确保在导出时使用了适当的参数,例如
dynamic、simplify等。以下是一个导出为 ONNX 的示例:from ultralytics import YOLO # 加载模型 model = YOLO("path/to/best.pt") # 导出模型 model.export(format="onnx", dynamic=True, simplify=True) -
推理设置:在进行推理时,确保使用相同的图像尺寸和其他推理参数。以下是一个推理示例:
# 使用 .pt 模型进行推理 results_pt = model.predict(source="path/to/image.jpg", imgsz=640) # 使用 .onnx 模型进行推理 model_onnx = YOLO("path/to/model.onnx") results_onnx = model_onnx.predict(source="path/to/image.jpg", imgsz=640) -
最小可复现示例:为了更好地帮助您解决问题,请提供一个最小可复现的代码示例。您可以参考我们的最小可复现示例指南来创建一个示例。
请尝试以上建议,如果问题仍然存在,请提供更多详细信息和代码示例,以便我们进一步调查。
希望这些信息对您有所帮助!如果有任何其他问题,请随时告知。
祝好, Ultralytics 团队
-
Lbj4175
你好,我和你有相同的问题,问题解决了吗
qcname
没有
Glenn JocherUltralytics您好,感谢您的反馈。导出为不同格式(如ONNX)时,检测结果可能会有所不同,通常是由于模型转换过程中精度损失或推理引擎差异导致的。建议您确保使用最新版本的Ultralytics和相关库,并尝试调整导出参数,如
dynamic=True或half=True。更多详情请参考导出文档。
Ibraheem-Ahmad
Hello! Would anyone be able to tell me why this code does not work: model.export(format=='onnx', int8 = True, dyamic = True, imgsz = (width,height))
the error I get is "TypeError: Model.export() takes 1 positional argument but 2 were given"
1
Glenn JocherUltralytics@Ibraheem-Ahmad hello! It looks like there's a small typo in your code that's causing the issue. In Python, when you're calling a function and passing arguments, you should use
=for assignment rather than==, which is used for comparison. Also, there's a typo indyamic, it should bedynamic. Here's the corrected line of code:model.export(format='onnx', int8=True, dynamic=True, imgsz=(width, height))This should work without any errors. If you have any more questions or run into issues, feel free to ask. Happy coding! 😊
Aisha-Hassan1
How can I path pictures and how many pictures?
Glenn JocherUltralytics@Aisha-Hassan1 hey there! 🌟 To pass multiple pictures for processing, you can use a directory, list, or wildcard as your
source. For example:# For a directory full of images model.predict(source='path/to/images/') # For specific images model.predict(source=['path/to/image1.jpg', 'path/to/image2.jpg']) # Using a wildcard model.predict(source='path/to/images/*.jpg')As for how many pictures, there's no strict limit—it depends on your system's capabilities. Just ensure your images comply with the model's input size, which you can adjust with the
imgszparameter if necessary. Happy coding! 😊1Aisha-Hassan1
When I don't put batch_size, the result is batch_size=1 .... code => [ Ultralytics YOLOv8.1.29 🚀 Python-3.11.5 torch-2.2.1+cpu CPU (Intel Core(TM) i5-3320M 2.60GHz) YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs
PyTorch: starting from 'yolov8n.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 84, 8400) (6.2 MB)
ONNX: starting export with onnx 1.15.0 opset 17... ONNX: export success ✅ 2.1s, saved as 'yolov8n.onnx' (12.1 MB)
Export complete (5.9s) Results saved to C:\Users\shosho Predict: yolo predict task=detect model=yolov8n.onnx imgsz=640 int8 Validate: yolo val task=detect model=yolov8n.onnx imgsz=640 data=coco.yaml int8 Visualize: https://netron.app
] .........batch_size = 4 model.export(format='onnx', int8=True, dynamic=True, batch=batch_size) res=>[Ultralytics YOLOv8.1.29 🚀 Python-3.11.5 torch-2.2.1+cpu CPU (Intel Core(TM) i5-3320M 2.60GHz) YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs
PyTorch: starting from 'yolov8n.pt' with input shape (4, 3, 640, 640) BCHW and output shape(s) (4, 84, 8400) (6.2 MB)
ONNX: starting export with onnx 1.15.0 opset 17... ONNX: export success ✅ 3.6s, saved as 'yolov8n.onnx' (12.1 MB)
Export complete (11.2s) Results saved to C:\Users\shosho Predict: yolo predict task=detect model=yolov8n.onnx imgsz=640 int8 Validate: yolo val task=detect model=yolov8n.onnx imgsz=640 data=coco.yaml int8 Visualize: https://netron.app 'yolov8n.onnx'] Is this the number of photos I should enter?
Aisha-Hassan1
import cv2 from ultralytics import YOLO
model = YOLO('yolov8n.pt') model.export(format='onnx', int8=True, dynamic=True) predicted_images = model.predict(source='G:/img') for i, result in enumerate(predicted_images): print(result) image = result.orig_img save_path = f'predicted_image_{i}.jpg'
cv2.imwrite(save_path, image)
print(f"Done{save_path}")The code works for me and saves the images, but I have two questions
1- How will i deal with an onnx file with JS and send it an array of images? 2- I want to export yolov5n-seg.pt to onnx to put a mask on the images?
Glenn JocherUltralytics@Aisha-Hassan1 hey there! 😊
- To deal with an ONNX file in JS and send it an array of images, you can use onnxjs for browser environments or onnxruntime-node for Node.js. Here’s an example using onnxjs:
async function runModel(inputImages) { const session = new onnx.InferenceSession(); await session.loadModel("path/to/your/model.onnx"); const inputTensors = inputImages.map(image => // convert your images to tensors); // Assuming you're working with one input named 'input' const feeds = { input: inputTensors }; const results = await session.run(feeds); return results; }- For exporting
yolov5n-seg.ptto ONNX with a mask, ensure your model supports segmentation tasks, then follow similar steps to exporting a detection model but make sure the output includes the segmentation masks. Your export code seems fine, but replaceyolov8n.ptwithyolov5n-seg.pt. Check model compatibility and output processing as per your needs!
If you need any more guidance, don't hesitate to ask. Have fun coding! ✨
1Aisha-Hassan1
The yolov5n-seg.pt export part show this error........[ ModuleNotFoundError Traceback (most recent call last) File G:\anaconda3\Lib\site-packages\ultralytics\nn\tasks.py:714, in torch_safe_load(weight) 707 with temporary_modules( 708 { 709 "ultralytics.yolo.utils": "ultralytics.utils", (...) 712 } 713 ): # for legacy 8.0 Classify and Pose models --> 714 ckpt = torch.load(file, map_location="cpu") 716 except ModuleNotFoundError as e: # e.name is missing module name
File G:\anaconda3\Lib\site-packages\torch\serialization.py:1026, in load(f, map_location, pickle_module, weights_only, mmap, **pickle_load_args) 1025 raise pickle.UnpicklingError(UNSAFE_MESSAGE + str(e)) from None -> 1026 return _load(opened_zipfile, 1027 map_location, 1028 pickle_module, 1029 overall_storage=overall_storage, 1030 **pickle_load_args) 1031 if mmap:
File G:\anaconda3\Lib\site-packages\torch\serialization.py:1438, in _load(zip_file, map_location, pickle_module, pickle_file, overall_storage, **pickle_load_args) 1437 unpickler.persistent_load = persistent_load -> 1438 result = unpickler.load() 1440 torch._utils._validate_loaded_sparse_tensors()
File G:\anaconda3\Lib\site-packages\torch\serialization.py:1431, in _load..UnpicklerWrapper.find_class(self, mod_name, name) 1430 mod_name = load_module_mapping.get(mod_name, mod_name) -> 1431 return super().find_class(mod_name, name)
ModuleNotFoundError: No module named 'models'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last) Cell In[2], line 1 ----> 1 model = YOLO('yolov5n-seg.pt')
File G:\anaconda3\Lib\site-packages\ultralytics\models\yolo\model.py:23, in YOLO.init(self, model, task, verbose) 20 self.dict = new_instance.dict 21 else: 22 # Continue with default YOLO initialization ---> 23 super().init(model=model, task=task, verbose=verbose)
File G:\anaconda3\Lib\site-packages\ultralytics\engine\model.py:142, in Model.init(self, model, task, verbose) 140 self._new(model, task=task, verbose=verbose) 141 else: --> 142 self._load(model, task=task) 144 self.model_name = model
File G:\anaconda3\Lib\site-packages\ultralytics\engine\model.py:229, in Model._load(self, weights, task) 227 suffix = Path(weights).suffix 228 if suffix == ".pt": --> 229 self.model, self.ckpt = attempt_load_one_weight(weights) 230 self.task = self.model.args["task"] 231 self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)
File G:\anaconda3\Lib\site-packages\ultralytics\nn\tasks.py:788, in attempt_load_one_weight(weight, device, inplace, fuse) 786 def attempt_load_one_weight(weight, device=None, inplace=True, fuse=False): 787 """Loads a single model weights.""" --> 788 ckpt, weight = torch_safe_load(weight) # load ckpt 789 args = {**DEFAULT_CFG_DICT, **(ckpt.get("train_args", {}))} # combine model and default args, preferring model args 790 model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
File G:\anaconda3\Lib\site-packages\ultralytics\nn\tasks.py:718, in torch_safe_load(weight) 716 except ModuleNotFoundError as e: # e.name is missing module name 717 if e.name == "models": --> 718 raise TypeError( 719 emojis( 720 f"ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained " 721 f"with https://github.com/ultralytics/yolov5.\nThis model is NOT forwards compatible with " 722 f"YOLOv8 at https://github.com/ultralytics/ultralytics." 723 f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to " 724 f"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'" 725 ) 726 ) from e 727 LOGGER.warning( 728 f"WARNING ⚠️ {weight} appears to require '{e.name}', which is not in ultralytics requirements." 729 f"\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future." 730 f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to " 731 f"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'" 732 ) 733 check_requirements(e.name) # install missing module
TypeError: ERROR yolov5n-seg.pt appears to be an Ultralytics YOLOv5 model originally trained with https://github.com/ultralytics/yolov5. This model is NOT forwards compatible with YOLOv8 at https://github.com/ultralytics/ultralytics. Recommend fixes are to train a new model using the latest 'ultralytics' package or to run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'
] part of the code in JS ...[
] show erro .........Access to fetch at 'file:///G:/pg_betch/yolov8n.onnx' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted. session.ts:61GET file:///G:/pg_betch/yolov8n.onnx net::ERR_FAILED(anonymous) @ session.ts:61 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 a @ onnx.min.js:14 Promise.then (async) s @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 r @ onnx.min.js:14 (anonymous) @ session.ts:48 t.event @ instrument.ts:294 (anonymous) @ session.ts:48 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 r @ onnx.min.js:14 e.loadModel @ onnx.min.js:14 t.loadModel @ inference-session-impl.ts:27 runModel @ index.html:11 (anonymous) @ index.html:27 session.ts:61
Uncaught (in promise) TypeError: Failed to fetch at e.<anonymous> (session.ts:61:34) at onnx.min.js:14:255680 at Object.next (onnx.min.js:14:255785) at a (onnx.min.js:14:254499)(anonymous) @ session.ts:61 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 a @ onnx.min.js:14 Promise.then (async) (anonymous) @ index.html:27
Glenn JocherUltralyticsHey there! It looks like you're encountering two different issues here:
-
Using an ONNX model with JavaScript: For running ONNX models in a browser with JavaScript, you're on the right track with onnx.js. However, loading local files directly can lead to CORS policy violations, as seen in your error. To fix this, serve your ONNX model from a server or use a cloud storage URL with proper CORS settings. Ensure your server or cloud storage is configured to allow such requests.
-
Exporting YOLOv5n-seg.pt to ONNX: The error suggests that the file
yolov5n-seg.ptmight be confused as a YOLOv5 model and you're trying to load it using YOLOv8, which leads to compatibility issues. Ifyolov5n-seg.ptis indeed a YOLOv5 model, ensure you're using the correct toolchain for export. For segmentation models with YOLOv8 (assumingyolov8n-seg.ptexists and it's what you meant), the export command you've used seems correct. Make sure you're within the Ultralytics ecosystem for YOLOv8 and its segmentation models, and check if there's a typo in the filename or a version mismatch. Correct model paths and compatible Ultralytics YOLO versions are crucial.
For working with segmentation models and applying masks to images post-export, you'll typically handle the output tensors from the ONNX model to extract segmentation masks and overlay them on the original images. This step will heavily depend on the output structure of your specific model.
Hope that helps! Keep experimenting, and feel free to reach out if you hit more snags. 😊
1-
Aisha-Hassan1
Can you help me how to handle the output tensors from the ONNX model to extract segmentation masks and overlay them on the original images ?
Glenn JocherUltralyticsHey there! 🙌 To handle output tensors from an ONNX model for segmentation tasks, you'll typically:
-
Run the Model: First, feed your input image to the ONNX model using your preferred ONNX runtime environment. This step returns the output tensors.
-
Process Output Tensors: For segmentation models, the output tensor usually represents either a pixel-wise class prediction or a set of masks for each detected object. You'll need to decode these tensors to get the segmentation masks. The exact processing will depend on your model's output format.
-
Overlay Masks on Original Images: Once you have the segmentation masks, you can overlay them on your original images. Here's a quick example in Python, assuming you have a mask:
import cv2 import numpy as np # Assuming 'image' is your original image and 'mask' is the segmentation mask # Ensure the mask is a binary mask (0 or 1) where 1 represents the segmented object overlay = cv2.addWeighted(image, 1, np.dstack((mask, mask, mask)) * 255, 0.5, 0) cv2.imwrite('segmented_image.jpg', overlay)For exporting
yolov5n-seg.ptor similar models to ONNX, you seem to have encountered an incompatibility issue indicating that you might be trying to load a YOLOv5 model with a YOLOv8 setup. Ensure you're using the proper version and tools for your specific YOLO model. YOLOv8 now has its dedicated ecosystem and might not directly support models trained with previous versions without conversion or specific handling.If YOLOv5 segmentation is what you need and you're dealing with
yolov5n-seg.pt, consider checking the YOLOv5 documentation for the precise export guidance. For segmentation tasks, you might need to adjust your approach tailored to the model's specific output layer design.Hope this helps! Let me know if there's anything else I can do for you. 😊
-
Aisha-Hassan1
Thank you very much for your help 1-Using an ONNX model with JavaScript:
Document<script> const labels = [ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", ]; const modelName = "yolov8n-seg.onnx"; const modelInputShape = [4, 3, 640, 640]; let mySession; const useState = (defaultValue) => { let value = defaultValue; const getValue = () => value; const setValue = (newValue) => (value = newValue); return [getValue, setValue]; }; const numClass = labels.length; const [session, setSession] = useState(null); cv["onRuntimeInitialized"] = async () => { // create session const [yolov8] = await Promise.all([ ort.InferenceSession.create(modelName), ]); mySession = setSession({ net: yolov8 }); const inputImages = [ "img/bb.jpg", "img/iam.jpg" ]; const inputTensors = await Promise.all(inputImages.map(async (imageUrl) => { const response = await fetch(imageUrl); if (!response.ok) { throw new Error(`Failed to fetch image: ${imageUrl}`); } const blob = await response.blob(); const image = await cv.imreadAsync(blob); const tensor = cv.tensorFromImageData(image); image.delete(); return tensor; })); // Assuming you're working with one input named 'input' const feeds = { input: inputTensors }; const results = await yolov8.run(feeds); console.log(results); // Assuming you need to handle the results here // Handle results... }; </script>problem of code In partial convert your images to tensors
Do you have a solution to the problem?
Glenn JocherUltralytics@Aisha-Hassan1 hey there! Thanks for reaching out 🌟. It looks like you're having a bit of trouble converting images to tensors in your JavaScript code while working with an ONNX model.
For the conversion part, using OpenCV.js to convert images to tensors might not directly align with the expected input format for ONNX models. Instead, you'll typically need to preprocess the images into a format that matches the expected input tensor of your ONNX model, including resizing images and normalizing pixel values if required.
A simplified approach (without OpenCV.js) could involve using standard JavaScript or browser APIs to load and preprocess your images before converting them into tensors. Unfortunately, detailed code for image preprocessing highly depends on the specific requirements of your ONNX model, such as input dimensions and pixel-value scaling.
Regarding overlaying segmentation masks (like from
yolov5n-seg.ptexported as ONNX) onto images using JavaScript:- Once you have your segmentation output from the model, it'll typically be a tensor where each value corresponds to a class prediction per pixel or a probability distribution across classes for each pixel.
- Convert this segmentation mask tensor back into an image format, applying any necessary thresholding to identify your classes of interest.
- Overlay this processed mask onto your original image. You can achieve this by manipulating the DOM directly in JavaScript or using canvas operations to blend images.
Both the conversion and overlay steps are somewhat intricate and depend heavily on the details of your model's output format as well as the web environment you're working in (pure JavaScript in the browser, Node.js, etc.).
For precise assistance, we might need more details on the output format of your segmentation model and the specific environment you're working in. Meanwhile, the Ultralytics Docs and YOLOv8's export mode provide a great starting point for deploying models efficiently across various platforms 🚀.
Hope this helps a bit! Keep exploring and don't hesitate to share more details or ask further questions. Happy coding!
Aisha-Hassan1
I would like answers to two other questions, please
1- If I want to enter an array of images in js to use batch, should I export onnx this way ? model.export(format='onnx', int8=True, dynamic=True) or Do I have to limit the number of photos like this? model.export(format='onnx', int8=True, dynamic=True, batch =number of images)
2- I want to run onnx in the GPU, what should I do?
Glenn JocherUltralyticsHey there! 😀 Glad you're exploring YOLOv8's capabilities. Let's dive into your questions:
-
Array of Images for Batch Inference in JS:
- Utilizing
dynamic=Trueduring export is the way to go if you plan on varying the batch size dynamically. There's no need to specify the batch size at export time for ONNX models, asdynamic=Trueenables the model to handle variable batch sizes. So, your first export command is spot on:model.export(format='onnx', int8=True, dynamic=True) - This setup allows you to feed different batch sizes at runtime without having to re-export the model for each specific batch size.
- Utilizing
-
Running ONNX on GPU:
- To run ONNX models on the GPU, ensure you have an ONNX runtime that supports GPU inference, such as ONNX Runtime-GPU. When initializing your inference session in your code, specify the GPU device. Here's a quick example if you're using Python:
import onnxruntime as ort # Specify the GPU device ort_session = ort.InferenceSession("your_model.onnx", providers=['CUDAExecutionProvider']) # Now you can run inference with ort_session and it should use the GPU - For JavaScript, the availability of GPU inference might be limited and typically runs on the CPU. ONNX.js primarily supports WebGL for some level of GPU acceleration in the browser, but true GPU computing might not be feasible directly in JS as it depends on the browser's capabilities and the onnxruntime-web package's support.
- To run ONNX models on the GPU, ensure you have an ONNX runtime that supports GPU inference, such as ONNX Runtime-GPU. When initializing your inference session in your code, specify the GPU device. Here's a quick example if you're using Python:
I hope this clears up your questions! Keep experimenting with YOLOv8, and don't hesitate to reach out if you have more questions. Happy coding! 🚀
-
Aisha-Hassan1
thank you so much code
 <script> var inputTensors=[]; const modelInputShape = [1, 3, 640, 640]; const divStride = (stride, width, height) => { if (width % stride !== 0) { if (width % stride >= stride / 2) width = (Math.floor(width / stride) + 1) * stride; else width = Math.floor(width / stride) * stride; } if (height % stride !== 0) { if (height % stride >= stride / 2) height = (Math.floor(height / stride) + 1) * stride; else height = Math.floor(height / stride) * stride; } return [width, height]; }; const preprocessing = (source, modelWidth, modelHeight, stride = 32) => { //const mat = cv.imread(source); // read from img tag const mat = cv.imread(document.getElementById(source)); const matC3 = new cv.Mat(mat.rows, mat.cols, cv.CV_8UC3); // new image matrix cv.cvtColor(mat, matC3, cv.COLOR_RGBA2BGR); // RGBA to BGR const [w, h] = divStride(stride, matC3.cols, matC3.rows); cv.resize(matC3, matC3, new cv.Size(w, h)); // padding image to [n x n] dim const maxSize = Math.max(matC3.rows, matC3.cols); // get max size from width and height const xPad = maxSize - matC3.cols, // set xPadding xRatio = maxSize / matC3.cols; // set xRatio const yPad = maxSize - matC3.rows, // set yPadding yRatio = maxSize / matC3.rows; // set yRatio const matPad = new cv.Mat(); // new mat for padded image cv.copyMakeBorder( matC3, matPad, 0, yPad, 0, xPad, cv.BORDER_CONSTANT, [0, 0, 0, 255] ); // padding black const input = cv.blobFromImage( matPad, 1 / 255.0, // normalize new cv.Size(modelWidth, modelHeight), // resize to model input size new cv.Scalar(0, 0, 0), true, // swapRB false // crop ); // preprocessing image matrix // release mat opencv mat.delete(); matC3.delete(); matPad.delete(); return [input, xRatio, yRatio]; }; const inputImages = [ "image1", "image2" ]; async function runModel(inputImages) { const [yolov8] = await Promise.all([ ort.InferenceSession.create("yolov8n-seg.onnx") ]); const [modelWidth, modelHeight] = modelInputShape.slice(2); for(let i=0 ; i<inputImages.length; i++){ const [input, xRatio, yRatio] = preprocessing( inputImages[i], modelWidth, modelHeight ); const tensor = new ort.Tensor("float32", input.data32F, modelInputShape); inputTensors[i]=tensor; console.log(inputTensors) } const { output0, output1 } = await yolov8.run({images:inputTensors}); console.log(output0); }; runModel(inputImages) </script>In the runModel function, I send it an array of images, and it makes an error in part
const { output0, output1 } = await yolov8.run({images:inputTensors})
Because inputTensors is an array
This is the form of error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'byteLength') at t.run (wasm-core-impl.ts:219:31) at t.run (proxy-wrapper.ts:215:17) at t.OnnxruntimeWebAssemblySessionHandler.run (session-handler.ts:84:15) at i.run (inference-session-impl.js:94:44) at runModel (main.html:94:55) t.run@wasm-core-impl.ts:219 t.run@proxy-wrapper.ts:215 run@session-handler.ts:84 run@inference-session-impl.js:94 runModel@main.html:94 await in runModel (async) (anonymous)@main.html:97
What is the solution to enter an array of images into the model?
Aisha-Hassan1
When using a array of objects, the first is taken only object
Glenn JocherUltralyticsHey there! Thanks for bringing this to our attention 🌟. When using an array of objects for inference with YOLOv8 in JavaScript, you'd typically batch the input images before sending them to the model. If you find that only the first object in your array is being processed, it might be related to how you're structuring the input data for the ONNX model.
For batch processing, ensure all your images are preprocessed (resized and normalized) correctly and then stacked into a single tensor that matches the ONNX model's expected input shape. The shape for a batch of images usually follows the format
[batch_size, channels, height, width]. It sounds like you might need to adjust how you're constructinginputTensorsto fit this expectation.Regarding running ONNX on a GPU, note that ONNX.js primarily targets web environments where direct access to the GPU through Web APIs (e.g., WebGL) might not fully leverage all GPU capabilities like a desktop environment would. If you're using ONNX in a server-side JavaScript environment (like with Node.js and onnxruntime-node), specifying the GPU for inference would depend on the capabilities of your specific backend setup and the ONNX runtime you're using. Onnxruntime-web currently doesn't offer direct control over executing models on GPU vs. CPU—it automatically utilizes available hardware acceleration like WebGL.
Here's a simplified structure for how you might handle batching:
async function runBatchModel(session, inputTensors) { // Ensure inputTensors is a batched tensor of the right shape const results = await session.run({input: inputTensors}); // Process results... }Remember to adjust the
runBatchModelfunction based on how your specific model expects inputs. Happy coding and don't hesitate to reach out if you have more questions! 😊Aisha-Hassan1
How to handle inputTensors in array of images?
Aisha-Hassan1
what is the datatybe of inputTensors
Glenn JocherUltralytics@Aisha-Hassan1 hey there! 🌟 The
inputTensorsis expected to be an array ofort.Tensorobjects where each tensor represents an image that has been correctly processed (resized, normalized) to match the input shape that your model expects.For instance, if you're preprocessing images for batch inference, each
ort.Tensorwould hold image data shaped according to the model's input specifications, typically[batch_size, channels, height, width]. If your model expects a single image of shape[1, 3, 640, 640], preprocess each image accordingly, and then stack them into an array.Here's a quick example on how you might prepare a single image:
const imageTensor = new ort.Tensor("float32", processedImageData, [1, 3, height, width]);And when you have multiple images prepared as tensors (
imageTensor1,imageTensor2, ...), you can put them in an array:const inputTensors = [imageTensor1, imageTensor2];Make sure each tensor in
inputTensorsfollows the model's expected input shape. Keep up the great work with ONNX models, and happy coding! 😄Aisha-Hassan1
erro ... wasm-core-impl.ts:219 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'byteLength') at t.run (wasm-core-impl.ts:219:31) at t.run (proxy-wrapper.ts:215:17) at t.OnnxruntimeWebAssemblySessionHandler.run (session-handler.ts:84:15) at i.run (inference-session-impl.js:94:44) at runModel (main.html:96:55) ........
when inputTensors => array const inputTensors = [imageTensor1, imageTensor2];
Aisha-Hassan1
[batch_size, channels, height, width]. If your model expects not a single image of shape ???
Glenn JocherUltralyticsHey there! 👋 When converting a YOLOv8 model for batch processing, you generally don't need to specify the batch size during export, especially with dynamic batching enabled. 🔄 Your export command:
model.export(format='onnx', int8=True, dynamic=True)is perfectly fine for creating an ONNX model that can handle arrays of images. Just ensure your data is prepped correctly when making actual predictions! 📊
For GPU acceleration with ONNX, leveraging frameworks like ONNX Runtime with CUDA support would be the way to go! 🔥 Make sure your environment is set up for GPU use, and you're specifying the execution provider accordingly.
Feel free to check out more on dynamic batching and ONNX export on the Ultralytics docs page! Hope this helps, and happy coding! 🚀
Aisha-Hassan1
code
const inputs = { images: [inputTensors[0], inputTensors[1]] };
const { output0, output1 } = await yolov8.run(inputs);
erro
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'byteLength') at t.run (wasm-core-impl.ts:219:31) at t.run (proxy-wrapper.ts:215:17) at t.OnnxruntimeWebAssemblySessionHandler.run (session-handler.ts:84:15) at i.run (inference-session-impl.js:94:44) at runModel (main.html:107:53)
Glenn JocherUltralyticsHey there! 👋 It looks like there might be a slight mix-up in how you're constructing the input to your model run. When dealing with arrays of tensors in ONNX.js, you should pass a single tensor that concatenates your image tensors along the batch dimension if the model is set up for batch processing.
For your issue with
inputTensorscausing an error aboutbyteLength, it's likely because the model expects one tensor that combines all input images. Instead of:const inputs = { images: [inputTensors[0], inputTensors[1]] };You should concatenate your
inputTensorsinto one tensor if your model expects a batch input. Unfortunately, directly passing an array like this might not work as expected with ONNX.js since it seems to expect the input as a single tensor representing the batch. The error you're encountering (TypeError: Cannot read properties of undefined (reading 'byteLength')) usually occurs when the input format to thesession.runmethod is not as expected.This could look different based on how your model is trained and how
ort.Tensorhandles batches. Ensure your model is trained with dynamic batch size if you want to process multiple images in a single forward pass. If you're not sure how to concatenate tensors in JavaScript (as direct tensor concatenation might not be as straightforward as in Python), you might have to loop over your images and process them one at a time, or look into adjusting your model to accept variable batch sizes more gracefully.Given your current setup, if your model does not explicitly support batched inputs, you might need to process each image individually:
for(const tensor of inputTensors) { const inputs = { images: tensor }; const outputs = await yolov8.run(inputs); // Process the outputs for each image here }Remember, different models expect the input in specific formats, including batch size. Ensure your preprocessing aligns with these expectations! 🚀
SugarSol
请问一下,YOLO26 在导出 onnx 时,imgsz参数取(384, 672)和(640, 640) 推理结果差异很大,是什么原因导致的呢?
Glenn JocherUltralyticsSugarSol
我使用的是官方提供的coco预训练权重直接导出onnx的,导出和预测都是使用的官方提供的代码,并未做任何修改,不同之处只有导出时的尺寸不同。奇怪的是,这种现象在YOLOv8中并未发现。
Glenn JocherUltralytics(수정됨)这更像是 YOLO26 的导出特性而不是 ONNX 本身的问题:YOLO26 的检测头是原生端到端(NMS-free)的,而 YOLOv8 是传统 NMS 流程,所以更换
imgsz时两者的一致性表现不一定相同;建议先在相同imgsz下对比.pt与.onnx的结果。end2end参数现已弃用并映射为nms:默认(不设置nms)导出与 YOLOv8 类似的原始预测,nms=False导出 NMS-free 输出,nms=True在支持的格式中内置 NMS,详见 导出文档 和 End-to-End 检测指南;如果方便,请贴出完整的导出/推理命令和yolo checks输出,我们再继续定位。SugarSol
YOLO26导出的onnx在相同形状下end2end与非end2end的推理输出是一致的。而.pt与.onnx的结果只有在导出为(640,640)的情况下一致,在此形状下的输出也与YOLOv8是一致的。下面是我的导出和预测脚本: from ultralytics import YOLO model = YOLO("./yolo26n.pt") path = model.export(format="onnx", imgsz=(384, 672), end2end=False) model = YOLO("./yolo26n.onnx") results = model("../../coco128/train2017/000000000049.jpg") results[0].save() 下面是不同形状的推理结果: (384,672): image 1/1 /home/easyits/ai/wpf/Employee/100/ultralytics/tools/../../coco128/train2017/000000000049.jpg: 384x672 1 person, 2 horses, 1 potted plant, 136.5ms Speed: 18.2ms preprocess, 136.5ms inference, 47.0ms postprocess per image at shape (1, 3, 384, 672) (640,640): image 1/1 /home/easyits/ai/wpf/Employee/100/ultralytics/tools/../../coco128/train2017/000000000049.jpg: 640x640 4 persons, 2 horses, 103.7ms Speed: 7.5ms preprocess, 103.7ms inference, 16.5ms postprocess per image at shape (1, 3, 640, 640)
Glenn JocherUltralytics你这个脚本里最需要先排除的是“对比条件不一致”:
.pt推理如果没显式传imgsz=(384, 672),通常还是按默认640跑,而导出的.onnx输入已经固定成(384, 672),所以这不算同尺度对比;建议先让.pt和.onnx在完全相同的imgsz下分别执行predict或直接val,导出模型本身也支持直接验证,可参考 检测任务中的导出说明;如果这样仍只有 YOLO26 在非640下不一致,请把两边的完整日志和yolo checks输出贴上来,我们继续查。SugarSol
抱歉,表达不是很清楚,我想表达的是导出和预测使用的是这样的命令,我在不同imgsz和end2end的组合下都对同一张图片进行了预测,确实是只有YOLO26在非640形状下与640形状下的结果不一致,只与imgsz有关,与是否为end2end无关。
Glenn JocherUltralytics感谢补充,这里基本可以定位到“矩形 ONNX 导出”的当前限制了:从当前 Exporter 实现参考 看,非 PyTorch 后端对非方形
imgsz不保证与.pt完全一致,导出完成时也会提示非方形imgsz的 non-PyTorchval不可用,所以你看到(384, 672)与640,640结果分叉、且与end2end无关,是符合现状的;如果目标是尽量和.pt对齐,建议优先用方形尺寸导出,例如imgsz=640或672,如果你希望我们继续跟进矩形输入场景,也请新开一个 issue 并附上完整日志和yolo checks输出。SugarSol
感谢您的回复,我提了issue#24428,并附上了完整日志和yolo checks输出。
Glenn JocherUltralytics感谢,已收到;这个问题我们就集中在
#24428里继续跟进,后续如能补充同一张图在.pt/.onnx下显式指定相同imgsz的model.predict()或model.val()对比结果,会更有助于确认是否是矩形导出的边界情况。
nwpu-caikun
I trained an image classification model. How can I perform incremental learning to add new class? Are there any methods other than retraining the model? big thanks
908637049 @.***
Glenn JocherUltralyticsAdding a new class changes the classifier head, so there isn’t a “no-training” way to truly add classes incrementally in Ultralytics YOLO classification; the recommended approach is to fine-tune from your existing checkpoint on a dataset that includes both the original classes and the new class to avoid catastrophic forgetting (see the Classification docs). Please remove the phone/email and keep details here in the discussion (public) so the team can help.
from ultralytics import YOLO model = YOLO("path/to/best.pt") # your previous classifier model.train(data="path/to/cls_dataset") # dataset now includes the new class
nwpu-caikun
we use a customed dataset to train a image classify model,when calculate the result conf,we meet a problem。 in the last layer, we manualy calculate the conf by logits output, and then ,softmax to generate the conf ,but the conf number is very low。 however,we try to print the rusult.prob, (results = model(image_path, verbose=False),results_probs_obj = results[0].probs ) we found the result.probs is not equal to manualy conf we calculate. the result.probs is much higher than manualy conf. result.probs is 99.998%, and manualy conf is only 6.1982%. what the difference between them? how the model calculate the conf, and get the 99.998% conf?
Glenn JocherUltralyticsresults[0].probsis already the final per-class probability vector (Softmax has been applied in the classification head during inference), so if you “manual softmax” a tensor that’s already probabilities you’ll get very different (often much smaller) numbers like your ~6%; if you want to reproduce Ultralytics’ confidence from logits, make sure you’re using the raw logits output (the classification head returns(probs, logits)in inference) and computetorch.softmax(logits, dim=1)once—see the Results/Probs API reference and the Classify head forward behavior.nwpu-caikun
how do I get the raw logits output after model(image), has any methods? when I get the raw logits output ,I can manual calculate the probs? thanks!
Glenn JocherUltralyticsmodel(image_path)goes throughClassificationPredictor.postprocess(), which intentionally keeps only the first element (preds[0]) when the model returns a tuple, so the raw logits aren’t exposed inResults; to get logits you need to run a PyTorch forward pass on the preprocessed tensor. (docs.ultralytics.com)import cv2 import torch from ultralytics import YOLO model = YOLO("path/to/best.pt") # classification .pt _ = model("path/to/image.jpg", verbose=False) # init predictor/transforms once img0 = cv2.imread("path/to/image.jpg") # BGR im = model.predictor.preprocess([img0]) with torch.no_grad(): probs, logits = model.model(im) # head returns (probs, logits) in inference probs_manual = torch.softmax(logits, dim=1)Note this tuple output is only available for PyTorch models; in export mode the head returns probabilities only. (docs.ultralytics.com)
sidshete
I have trained model for instance segmentation and I ma trying to export to run on DPU. Here is the code mentioned below
from ultralytics import YOLO
best_weights_path = "../weights/yolo11_s/yolo11_s.pt" data_yaml = "../yolo_seg/dataset.yaml"
model = YOLO(best_weights_path)
Export for DPU (INT8)
model.export( format="onnx", data=data_yaml,
int8=True,
simplify=True, nms=False
)I get the following error.
UnpicklingError Traceback (most recent call last) Cell In[18], line 6 3 best_weights_path = "../weights/yolo11_s/yolo11_s.pt" 4 calib_data_yaml = "../dataset.yaml" ----> 6 model = YOLO(best_weights_path) 8 # Export for DPU (INT8) 9 model.export( 10 format="onnx", 11 data=calib_data_yaml, # calibration dataset required for INT8 (...) 14 nms=False # often applied post-inference 15 )
File ~/testing_env/lib/python3.10/site-packages/ultralytics/models/yolo/model.py:23, in YOLO.init(self, model, task, verbose) 20 self.dict = new_instance.dict 21 else: 22 # Continue with default YOLO initialization ---> 23 super().init(model=model, task=task, verbose=verbose)
File ~/testing_env/lib/python3.10/site-packages/ultralytics/engine/model.py:151, in Model.init(self, model, task, verbose) 149 self._new(model, task=task, verbose=verbose) 150 else: --> 151 self._load(model, task=task)
File ~/testing_env/lib/python3.10/site-packages/ultralytics/engine/model.py:240, in Model._load(self, weights, task) 237 weights = checks.check_model_file_from_stem(weights) # add suffix, i.e. yolov8n -> yolov8n.pt 239 if Path(weights).suffix == ".pt": --> 240 self.model, self.ckpt = attempt_load_one_weight(weights) 241 self.task = self.model.args["task"] 242 self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)
File ~/testing_env/lib/python3.10/site-packages/ultralytics/nn/tasks.py:806, in attempt_load_one_weight(weight, device, inplace, fuse) 804 def attempt_load_one_weight(weight, device=None, inplace=True, fuse=False): 805 """Loads a single model weights.""" --> 806 ckpt, weight = torch_safe_load(weight) # load ckpt 807 args = {**DEFAULT_CFG_DICT, **(ckpt.get("train_args", {}))} # combine model and default args, preferring model args 808 model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
File ~/testing_env/lib/python3.10/site-packages/ultralytics/nn/tasks.py:732, in torch_safe_load(weight) 724 try: 725 with temporary_modules( 726 { 727 "ultralytics.yolo.utils": "ultralytics.utils", (...) 730 } 731 ): # for legacy 8.0 Classify and Pose models --> 732 ckpt = torch.load(file, map_location="cpu") 734 except ModuleNotFoundError as e: # e.name is missing module name 735 if e.name == "models":
File ~/testing_env/lib/python3.10/site-packages/torch/serialization.py:1524, in load(f, map_location, pickle_module, weights_only, mmap, **pickle_load_args) 1516 return _load( 1517 opened_zipfile, 1518 map_location, (...) 1521 **pickle_load_args, 1522 ) 1523 except pickle.UnpicklingError as e: -> 1524 raise pickle.UnpicklingError(_get_wo_message(str(e))) from None 1525 return _load( 1526 opened_zipfile, 1527 map_location, (...) 1530 **pickle_load_args, 1531 ) 1532 if mmap:
UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint. (1) In PyTorch 2.6, we changed the default value of the
weights_onlyargument intorch.loadfromFalsetoTrue. Re-runningtorch.loadwithweights_onlyset toFalsewill likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source. (2) Alternatively, to load withweights_only=Trueplease check the recommended steps in the following error message. WeightsUnpickler error: Unsupported global: GLOBAL ultralytics.nn.modules.block.C3k2 was not an allowed global by default. Please usetorch.serialization.add_safe_globals([ultralytics.nn.modules.block.C3k2])or thetorch.serialization.safe_globals([ultralytics.nn.modules.block.C3k2])context manager to allowlist this global if you trust this class/function.
Glenn JocherUltralytics(수정됨)That error is coming from PyTorch 2.6's new default
torch.load(weights_only=True), which blocks custom Ultralytics layers likeultralytics.nn.modules.block.C3k2. First upgrade withpip install -U ultralytics; if you still hit it and trust the checkpoint, either pin PyTorch<2.6or allowlistC3k2before callingYOLO():import torch from ultralytics import YOLO from ultralytics.nn.modules.block import C3k2 torch.serialization.add_safe_globals([C3k2]) # only if you trust the .pt source model = YOLO("../weights/yolo11_s/yolo11_s.pt")Also note that INT8 ONNX export is supported in current Ultralytics: use
quantize=8(the olderint8=Trueis mapped to it) together withdatapointing to your calibration dataset. If your DPU toolchain needs its own quantizer, you can instead export FP32 ONNX and quantize with your vendor toolchain; see the supported export args in the Export mode docs and ONNX export guide.If you paste
!yolo checks(and restart the notebook kernel if you recently upgraded PyTorch/Ultralytics), I can confirm the exact version combo that's triggering this on your side.
GeThi255
Hi, export to "tflite" and other is not working with python 3.13, 3.10. or 3.08 due to incompatibility of e.g. tensorflow version (Ultralytics requirement ['tensorflow>=2.0.0,<=2.19.0'] ). Tested on windows 11 and Raspi. Could you please check. Thanks Gerd
404-NOTFOUND-Coder
Title: int8 argument not supported when exporting to ONNX in Ultralytics 8.3.162
Description:
I encountered an error when trying to export a trained YOLOv8 model to ONNX format with the following code:
model = YOLO('/kb210/wrs/tennis-analysis/tennis_analysis/training/runs/detect/train27/weights/best.pt') model.export(format="onnx", imgsz=(1024,1280), nms=True, int8=True, dynamic=True) The error traceback is as follows:
Traceback (most recent call last): File "/kb210/wrs/tennis-analysis/tennis_analysis/yolo_inference.py", line 15, in model.export(format="onnx", imgsz=(1024,1280), nms=True, int8=True, dynamic=True) File "/kb210/conda/envs/tennis_analysis/lib/python3.9/site-packages/ultralytics/engine/model.py", line 819, in export return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model) File "/kb210/conda/envs/tennis_analysis/lib/python3.9/site-packages/ultralytics/engine/exporter.py", line 311, in call validate_args(fmt, self.args, fmt_keys) File "/kb210/conda/envs/tennis_analysis/lib/python3.9/site-packages/ultralytics/engine/exporter.py", line 171, in validate_args assert arg in valid_args, f"ERROR ❌️ argument '{arg}' is not supported for format='{format}'" AssertionError: ERROR ❌️ argument 'int8' is not supported for format='onnx' From the error message, it seems that the int8=True argument is not supported for ONNX export. However, I believe INT8 quantization could be useful for optimizing models even before deployment to certain runtimes (e.g., TensorRT).
Question:
Is there any plan to support INT8 during ONNX export? If not, what would be the recommended way to apply INT8 quantization after exporting to ONNX?
Environment:
Ultralytics version: 8.3.162 Python version: 3.9.19 PyTorch version: 1.13.1 OS: Linux Hardware: Intel Xeon E5-2680 v4 2.40GHz Thanks for your help!
rememberBr
Does using dynamic=True on Nvidia's Jetson development board not include batch dimension? It seems that only w and h have become dynamic dimensions, while batch is fixed at 1?
