Skip to content

Commit 0e51495

Browse files
committed
replace onnxsim with onnxslim
1 parent aad320d commit 0e51495

File tree

7 files changed

+21
-16
lines changed

7 files changed

+21
-16
lines changed

docker/Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ ADD https://github.com/ultralytics/assets/releases/download/v0.0.0/Arial.ttf \
1414
# Install linux packages
1515
# g++ required to build 'tflite_support' and 'lap' packages, libusb-1.0-0 required for 'tflite_support' package
1616
RUN apt update \
17-
&& apt install --no-install-recommends -y gcc git zip curl htop libgl1 libglib2.0-0 libpython3-dev gnupg g++ libusb-1.0-0
17+
&& apt install --no-install-recommends -y gcc git zip curl htop libgl1 libglib2.0-0 libpython3-dev gnupg g++ libusb-1.0-0 build-essential
1818

1919
# Security updates
2020
# https://security.snyk.io/vuln/SNYK-UBUNTU1804-OPENSSL-3314796

docs/en/modes/export.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ This table details the configurations and options available for exporting YOLO m
8383
| `half` | `bool` | `False` | Enables FP16 (half-precision) quantization, reducing model size and potentially speeding up inference on supported hardware. |
8484
| `int8` | `bool` | `False` | Activates INT8 quantization, further compressing the model and speeding up inference with minimal accuracy loss, primarily for edge devices. |
8585
| `dynamic` | `bool` | `False` | Allows dynamic input sizes for ONNX and TensorRT exports, enhancing flexibility in handling varying image dimensions. |
86-
| `simplify` | `bool` | `False` | Simplifies the model graph for ONNX exports, potentially improving performance and compatibility. |
86+
| `simplify` | `bool` | `False` | Simplifies the model graph for ONNX exports with `onnxsim`, potentially improving performance and compatibility. |
8787
| `opset` | `int` | `None` | Specifies the ONNX opset version for compatibility with different ONNX parsers and runtimes. If not set, uses the latest supported version. |
8888
| `workspace` | `float` | `4.0` | Sets the maximum workspace size in GB for TensorRT optimizations, balancing memory usage and performance. |
8989
| `nms` | `bool` | `False` | Adds Non-Maximum Suppression (NMS) to the CoreML export, essential for accurate and efficient detection post-processing. |

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ onnxruntime==1.15.1
55
pycocotools==2.0.7
66
PyYAML==6.0.1
77
scipy==1.13.0
8-
onnxsim==0.4.36
8+
onnxslim==0.1.28
99
onnxruntime-gpu==1.18.0
1010
gradio==4.31.5
1111
opencv-python==4.9.0.80

ultralytics/cfg/default.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ keras: False # (bool) use Kera=s
8282
optimize: False # (bool) TorchScript: optimize for mobile
8383
int8: False # (bool) CoreML/TF INT8 quantization
8484
dynamic: False # (bool) ONNX/TF/TensorRT: dynamic axes
85-
simplify: False # (bool) ONNX: simplify model
85+
simplify: False # (bool) ONNX: simplify model using `onnxslim`
8686
opset: # (int, optional) ONNX: opset version
8787
workspace: 4 # (int) TensorRT: workspace size (GB)
8888
nms: False # (bool) CoreML: add NMS

ultralytics/engine/exporter.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ def export_onnx(self, prefix=colorstr("ONNX:")):
355355
"""YOLOv8 ONNX export."""
356356
requirements = ["onnx>=1.12.0"]
357357
if self.args.simplify:
358-
requirements += ["onnxsim>=0.4.33", "onnxruntime-gpu" if torch.cuda.is_available() else "onnxruntime"]
358+
requirements += ["onnxslim==0.1.28", "onnxruntime" + ("-gpu" if torch.cuda.is_available() else "")]
359359
if ARM64:
360360
check_requirements("cmake") # 'cmake' is needed to build onnxsim on aarch64
361361
check_requirements(requirements)
@@ -394,14 +394,17 @@ def export_onnx(self, prefix=colorstr("ONNX:")):
394394
# Simplify
395395
if self.args.simplify:
396396
try:
397-
import onnxsim
398-
399-
LOGGER.info(f"{prefix} simplifying with onnxsim {onnxsim.__version__}...")
400-
# subprocess.run(f'onnxsim "{f}" "{f}"', shell=True)
401-
model_onnx, check = onnxsim.simplify(model_onnx)
402-
assert check, "Simplified ONNX model could not be validated"
397+
import onnxslim
398+
399+
LOGGER.info(f"{prefix} simplifying with onnxslim {onnxslim.__version__}...")
400+
model_onnx = onnxslim.slim(model_onnx)
401+
402+
# ONNX Simplifier (deprecated as must be compiled with 'cmake' in aarch64 and Conda CI environments)
403+
# import onnxsim
404+
# model_onnx, check = onnxsim.simplify(model_onnx)
405+
# assert check, "Simplified ONNX model could not be validated"
403406
except Exception as e:
404-
LOGGER.info(f"{prefix} simplifier failure: {e}")
407+
LOGGER.warning(f"{prefix} simplifier failure: {e}")
405408

406409
# Metadata
407410
for k, v in self.metadata.items():
@@ -656,7 +659,7 @@ def export_coreml(self, prefix=colorstr("CoreML:")):
656659
def export_engine(self, prefix=colorstr("TensorRT:")):
657660
"""YOLOv8 TensorRT export https://developer.nvidia.com/tensorrt."""
658661
assert self.im.device.type != "cpu", "export running on CPU but must be on GPU, i.e. use 'device=0'"
659-
f_onnx, _ = self.export_onnx() # run before trt import https://github.com/ultralytics/ultralytics/issues/7016
662+
f_onnx, _ = self.export_onnx() # run before TRT import https://github.com/ultralytics/ultralytics/issues/7016
660663

661664
try:
662665
import tensorrt as trt # noqa
@@ -741,7 +744,7 @@ def export_saved_model(self, prefix=colorstr("TensorFlow SavedModel:")):
741744
"onnx>=1.12.0",
742745
"onnx2tf>=1.15.4,<=1.17.5",
743746
"sng4onnx>=1.0.1",
744-
"onnxsim>=0.4.33",
747+
"onnxslim==0.1.28",
745748
"onnx_graphsurgeon>=0.3.26",
746749
"tflite_support",
747750
"flatbuffers>=23.5.26,<100", # update old 'flatbuffers' included inside tensorflow package

ultralytics/nn/modules/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
m = Conv(128, 128)
1414
f = f'{m._get_name()}.onnx'
1515
torch.onnx.export(m, x, f)
16-
os.system(f'onnxsim {f} {f} && open {f}')
16+
os.system(f'onnxslim {f} {f} && open {f}') # pip install onnxslim
1717
```
1818
"""
1919

ultralytics/utils/benchmarks.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,8 @@ def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
323323

324324
input_tensor = sess.get_inputs()[0]
325325
input_type = input_tensor.type
326+
dynamic = not all(isinstance(dim, int) and dim >= 0 for dim in input_tensor.shape) # dynamic input shape
327+
input_shape = (1, 3, self.imgsz, self.imgsz) if dynamic else input_tensor.shape
326328

327329
# Mapping ONNX datatype to numpy datatype
328330
if "float16" in input_type:
@@ -338,7 +340,7 @@ def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
338340
else:
339341
raise ValueError(f"Unsupported ONNX datatype {input_type}")
340342

341-
input_data = np.random.rand(*input_tensor.shape).astype(input_dtype)
343+
input_data = np.random.rand(*input_shape).astype(input_dtype)
342344
input_name = input_tensor.name
343345
output_name = sess.get_outputs()[0].name
344346

0 commit comments

Comments
 (0)