Repository: ultralytics/ultralytics

Issue:
模型转换错误 :TensorRT: export failure ❌ 0.0s: max() arg is an empty sequence    
### Search before asking

- [X] I have searched the YOLOv8 [issues](https://github.com/ultralytics/ultralytics/issues) and found no similar bug report.


### YOLOv8 Component

Export

### Bug

(yolov8_seg) wudengchao@wudengchao:~/ultralytics-main$ python
Python 3.8.18 (default, Sep 11 2023, 13:40:15) 
[GCC 11.2.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ultralytics import YOLO
>>> model = YOLO('yolov8m.pt')
>>> model.export(format='engine')
WARNING ⚠️ TensorRT requires GPU export, automatically assigning device=0
Ultralytics YOLOv8.1.44 🚀 Python-3.8.18 torch-1.12.1+cu116 CUDA:0 (NVIDIA RTX A2000 12GB, 12036MiB)
YOLOv8m summary (fused): 218 layers, 25886080 parameters, 0 gradients, 78.9 GFLOPs

PyTorch: starting from 'yolov8m.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 84, 8400) (49.7 MB)
ONNX: export failure ❌ 0.0s: max() arg is an empty sequence
TensorRT: export failure ❌ 0.0s: max() arg is an empty sequence
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/model.py", line 601, in export
    return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)
  File "/home/wudengchao/.conda/envs/yolov8_seg/lib/python3.8/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/exporter.py", line 286, in __call__
    f[1], _ = self.export_engine()
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/exporter.py", line 139, in outer_func
    raise e
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/exporter.py", line 134, in outer_func
    f, model = inner_func(*args, **kwargs)
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/exporter.py", line 657, in export_engine
    f_onnx, _ = self.export_onnx()  # run before trt import https://github.com/ultralytics/ultralytics/issues/7016
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/exporter.py", line 139, in outer_func
    raise e
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/exporter.py", line 134, in outer_func
    f, model = inner_func(*args, **kwargs)
  File "/home/wudengchao/ultralytics-main/ultralytics/engine/exporter.py", line 362, in export_onnx
    opset_version = self.args.opset or get_latest_opset()
  File "/home/wudengchao/ultralytics-main/ultralytics/utils/torch_utils.py", line 393, in get_latest_opset
    return max(int(k[14:]) for k in vars(torch.onnx) if "symbolic_opset" in k) - 1  # opset
ValueError: max() arg is an empty sequence

### Environment

Ultralytics YOLOv8.1.44 🚀 Python-3.8.18 torch-1.12.1+cu116 CUDA:0 (NVIDIA RTX A2000 12GB, 12036MiB)

### Minimal Reproducible Example

_No response_

### Additional

_No response_

### Are you willing to submit a PR?

- [ ] Yes I'd like to help by submitting a PR!


Discussion:
👋 Hello @abcc235, thank you for your interest in Ultralytics YOLOv8 🚀! We recommend a visit to the [Docs](https://docs.ultralytics.com) for new users where you can find many [Python](https://docs.ultralytics.com/usage/python/) and [CLI](https://docs.ultralytics.com/usage/cli/) usage examples and where many of the most common questions may already be answered.

If this is a 🐛 Bug Report, please provide a [minimum reproducible example](https://docs.ultralytics.com/help/minimum_reproducible_example/) to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our [Tips for Best Training Results](https://docs.ultralytics.com/yolov5/tutorials/tips_for_best_training_results/).

Join the vibrant [Ultralytics Discord](https://ultralytics.com/discord) 🎧 community for real-time conversations and collaborations. This platform offers a perfect space to inquire, showcase your work, and connect with fellow Ultralytics users.

## Install

Pip install the `ultralytics` package including all [requirements](https://github.com/ultralytics/ultralytics/blob/main/pyproject.toml) in a [**Python>=3.8**](https://www.python.org/) environment with [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/).

```bash
pip install ultralytics
```

## Environments

YOLOv8 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):

- **Notebooks** with free GPU: <a href="https://console.paperspace.com/github/ultralytics/ultralytics"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run on Gradient"/></a> <a href="https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a> <a href="https://www.kaggle.com/ultralytics/yolov8"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)
- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)
- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href="https://hub.docker.com/r/ultralytics/ultralytics"><img src="https://img.shields.io/docker/pulls/ultralytics/ultralytics?logo=docker" alt="Docker Pulls"></a>

## Status

<a href="https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml?query=event%3Aschedule"><img src="https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml/badge.svg" alt="Ultralytics CI"></a>

If this badge is green, all [Ultralytics CI](https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml?query=event%3Aschedule) tests are currently passing. CI tests verify correct operation of all YOLOv8 [Modes](https://docs.ultralytics.com/modes/) and [Tasks](https://docs.ultralytics.com/tasks/) on macOS, Windows, and Ubuntu every 24 hours and on every commit.
The yolov8m.pt used above are all just downloaded from the official website
I reinstalled version 8.1.18 of ultralytics to solve the above issue, indicating a bug in model conversion using version 8.1.44.
@abcc235 thank you for sharing your experience and workaround with the community! It's great to hear that reverting to version 8.1.18 of Ultralytics solved the model conversion issue you encountered with version 8.1.44. 🚀

Your insight helps us identify areas for improvement. We appreciate your contribution and encourage you to continue engaging with us. If you have any more details that might help us replicate and address this bug, please feel free to share!

```bash
# For community members encountering a similar issue, here's how to install a specific version of Ultralytics YOLO:
pip install ultralytics==8.1.18
```

Thanks again for your valuable feedback! If there's anything else we can help with, please let us know.
I had the same problem with the latest version 8.2.😢
Hey there! 👋 Sorry to hear you've encountered the same problem. 😢 A potential quick fix might be to revert to a version that works without this issue, say 8.1.18. You can do this by running:

```bash
pip install ultralytics==8.1.18
```

In the meantime, we'll look into the issue with version 8.2. Thanks for bringing this to our attention! Stay tuned for updates. 🚀
I had the same problem on jetson nano。
![image](https://github.com/ultralytics/ultralytics/assets/76209259/3b67daf1-e7de-4b6d-bd11-97b41a05aadc)
There have no "symbolic_opset" in vars(torch.onnx) with torch1.11 and onnx1.16.
```
>>> import torchT
>>> vars(torch.onnx)
{'__name__': 'torch.onnx', '__doc__': None, '__package__': 'torch.onnx', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f40d28e80>, '__spec__': ModuleSpec(name='torch.onnx', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f40d28e80>, origin='/home/rht/mambaforge/envs/yolo/lib/python3.8/site-packages/torch/onnx/__init__.py', submodule_search_locations=['/home/rht/mambaforge/envs/yolo/lib/python3.8/site-packages/torch/onnx']), '__path__': ['/home/rht/mambaforge/envs/yolo/lib/python3.8/site-packages/torch/onnx'], '__file__': '/home/rht/mambaforge/envs/yolo/lib/python3.8/site-packages/torch/onnx/__init__.py', '__cached__': '/home/rht/mambaforge/envs/yolo/lib/python3.8/site-packages/torch/onnx/__pycache__/__init__.cpython-38.pyc', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'copyright': Copyright (c) 2001-2023 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object., '__pybind11_internals_v4_clang_libstdcpp_cxxabi1002__': <capsule object NULL at 0x7f4ba5c750>, '_': None}, '_C': <module 'torch._C' from '/home/rht/mambaforge/envs/yolo/lib/python3.8/site-packages/torch/_C.cpython-38-aarch64-linux-gnu.so'>, 'TensorProtoDataType': <class 'torch._C._onnx.TensorProtoDataType'>, 'OperatorExportTypes': <class 'torch._C._onnx.OperatorExportTypes'>, 'TrainingMode': <class 'torch._C._onnx.TrainingMode'>, 'PYTORCH_ONNX_CAFFE2_BUNDLE': False, 'ONNX_ARCHIVE_MODEL_PROTO_NAME': '__MODEL_PROTO', 'producer_name': 'pytorch', 'producer_version': '1.11.0', 'ExportTypes': <class 'torch.onnx.ExportTypes'>, 'CheckerError': <class 'torch.onnx.CheckerError'>, '_export': <function _export at 0x7f40d404c0>, 'export': <function export at 0x7f40d40550>, 'export_to_pretty_string': <function export_to_pretty_string at 0x7f40d405e0>, '_optimize_trace': <function _optimize_trace at 0x7f40d40670>, 'select_model_mode_for_export': <function select_model_mode_for_export at 0x7f40d40700>, '_run_symbolic_function': <function _run_symbolic_function at 0x7f40d40790>, '_run_symbolic_method': <function _run_symbolic_method at 0x7f40d40820>, 'is_in_onnx_export': <function is_in_onnx_export at 0x7f40d408b0>, 'register_custom_op_symbolic': <function register_custom_op_symbolic at 0x7f40d40940>, 'unregister_custom_op_symbolic': <function unregister_custom_op_symbolic at 0x7f40d409d0>}
```
I successfully exported after manually specifying opset=11 in cil
![image](https://github.com/ultralytics/ultralytics/assets/76209259/dd3813cc-73f2-44e9-a11d-5503f363cdd2)
I guess it needs another way to get the available opset. Or add tips to the guide🤔


Hey there! 😊 It looks like you've encountered a known issue with the `get_latest_opset()` function that occurs under specific configurations, particularly with certain versions of PyTorch and ONNX where the `symbolic_opset` entries aren't present as expected. Your workaround of manually specifying the opset version (`opset=11`) is spot-on! 

Here's how you can efficiently set the opset in your export call if others encounter this issue:

```python
from ultralytics import YOLO
model = YOLO('yolov8m.pt')
model.export(format='onnx', opset=11)
```

We appreciate this insight! We're looking into enhancing our version compatibility checks or updating the documentation to help navigate such issues more smoothly. 🚀 Thanks for sharing your solution!

Resolving patch:
diff --git a/ultralytics/__init__.py b/ultralytics/__init__.py
--- a/ultralytics/__init__.py
+++ b/ultralytics/__init__.py
@@ -1,6 +1,6 @@
 # Ultralytics YOLO 🚀, AGPL-3.0 license
 
-__version__ = "8.2.14"
+__version__ = "8.2.15"
 
 from ultralytics.data.explorer.explorer import Explorer
 from ultralytics.models import RTDETR, SAM, YOLO, YOLOWorld
diff --git a/ultralytics/utils/torch_utils.py b/ultralytics/utils/torch_utils.py
--- a/ultralytics/utils/torch_utils.py
+++ b/ultralytics/utils/torch_utils.py
@@ -399,8 +399,13 @@ def copy_attr(a, b, include=(), exclude=()):
 
 
 def get_latest_opset():
-    """Return second-most (for maturity) recently supported ONNX opset by this version of torch."""
-    return max(int(k[14:]) for k in vars(torch.onnx) if "symbolic_opset" in k) - 1  # opset
+    """Return the second-most recent ONNX opset version supported by this version of PyTorch, adjusted for maturity."""
+    if TORCH_1_13:
+        # If the PyTorch>=1.13, dynamically compute the latest opset minus one using 'symbolic_opset'
+        return max(int(k[14:]) for k in vars(torch.onnx) if "symbolic_opset" in k) - 1
+    # Otherwise for PyTorch<=1.12 return the corresponding predefined opset
+    version = torch.onnx.producer_version.rsplit(".", 1)[0]  # i.e. '2.3'
+    return {"1.12": 15, "1.11": 14, "1.10": 13, "1.9": 12, "1.8": 12}.get(version, 12)
 
 
 def intersect_dicts(da, db, exclude=()):


Test patch: