ONNX export of MaskRCNN: inference fails when no detections are present
🐛 Bug
After exporting MaskRCNN to ONNX, inference works correctly on images on which there are detection. However, when trying to infer on a tensor that will have nothing detected on it, exception is thrown:
[E:onnxruntime:, sequential_executor.cc:183 Execute] Non-zero status code returned while running ReduceMax node. Name:'' Status Message: /onnxruntime_src/onnxruntime/core/providers/cuda/reduction/reduction_ops.cc:110 onnxruntime::common::Status onnxruntime::cuda::PrepareForReduce(onnxruntime::OpKernelContext*, bool, const std::vector<long int>&, const onnxruntime::Tensor**, onnxruntime::Tensor**, int64_t&, int64_t&, std::vector<long int>&, std::vector<long int>&, std::vector<long int>&) keepdims || dim != 0 was false. Can't reduce on dim with value of 0 if 'keepdims' is false. Invalid output shape would be produced. input_shape:{0,4}
To Reproduce
Steps to reproduce the behavior:
1.Export a pretrained MaskRCNN model:
torch.onnx.export(
model,
input_tensor.float(),
onnx_model_filepath,
export_params=True,
opset_version=11,
do_constant_folding=True,
verbose=False,
input_names=["input"],
output_names=["output"],
dynamic_axes={"input": {0: "batch_size"}, "output: {0: "batch_size"}},
)
- Infer on an image that has detections:
ort_session = onnxruntime.InferenceSession(onnx_model_filepath)
input_array = input_tensor.cpu().numpy()
ort_inputs = {"input": input_array}
for i in tqdm(range(1), desc="ort_session.run"):
ort_outputs = ort_session.run(None, ort_inputs)
No exceptions here. Now 3. Infer on an image that will have no detections, ex. a random one:
random_tensor = torch.randn(input_tensor.shape)
random_array = random_tensor.cpu().numpy()
ort_inputs = {"input": random_array}
for i in tqdm(range(1), desc="ort_session.run"):
ort_outputs = ort_session.run(None, ort_inputs)
This throws the exception:
`[E:onnxruntime:, sequential_executor.cc:183 Execute] Non-zero status code returned while running ReduceMax node. Name:'' Status Message: /onnxruntime_src/onnxruntime/core/providers/cuda/reduction/reduction_ops.cc:110 onnxruntime::common::Status onnxruntime::cuda::PrepareForReduce(onnxruntime::OpKernelContext*, bool, const std::vector<long int>&, const onnxruntime::Tensor**, onnxruntime::Tensor**, int64_t&, int64_t&, std::vector<long int>&, std::vector<long int>&, std::vector<long int>&) keepdims || dim != 0 was false. Can't reduce on dim with value of 0 if 'keepdims' is false. Invalid output shape would be produced. input_shape:{0,4}`
Stacktrace:
ort_session.run: 0%| | 0/1 [00:00<?, ?it/s]
Traceback (most recent call last):
File "maskrcnn_deployment.py", line 205, in infer_onnx_model
ort_outputs = ort_session.run(None, ort_inputs)
File "/.../lib/python3.6/site-packages/onnxruntime/capi/session.py", line 144, in run
return self._sess.run(output_names, input_feed, run_options)
onnxruntime.capi.onnxruntime_pybind11_state.RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running ReduceMax node. Name:'' Status Message: /onnxruntime_src/onnxruntime/core/providers/cuda/reduction/reduction_ops.cc:110 onnxruntime::common::Status onnxruntime::cuda::PrepareForReduce(onnxruntime::OpKernelContext*, bool, const std::vector<long int>&, const onnxruntime::Tensor**, onnxruntime::Tensor**, int64_t&, int64_t&, std::vector<long int>&, std::vector<long int>&, std::vector<long int>&) keepdims || dim != 0 was false. Can't reduce on dim with value of 0 if 'keepdims' is false. Invalid output shape would be produced. input_shape:{0,4}
Expected behavior
I would expect to obtain output from the ONNX exported MaskRCNN similar to the output from PyTorch version, i.e. a list of "boxes", "labels", "scores" and "masks", with their 1st dimension = 0
Environment
PlPyTorch version: 1.4.0
Is debug build: No
CUDA used to build PyTorch: 10.1
OS: Ubuntu 18.04.3 LTS
GCC version: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
CMake version: Could not collect
Python version: 3.6
Is CUDA available: Yes
CUDA runtime version: 10.0.130
GPU models and configuration:
GPU 0: GeForce RTX 2080 Ti
GPU 1: GeForce RTX 2080 Ti
GPU 2: GeForce RTX 2080 Ti
GPU 3: GeForce RTX 2080 Ti
Nvidia driver version: 418.87.01
cuDNN version: /usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.4
Versions of relevant libraries:
[pip3] numpy==1.18.1
[pip3] torch==1.4.0
[pip3] torchvision==0.5.0
[conda] Could not collect
Also:
[pip3] onnx==1.6.0
[pip3] onnxruntime==1.1.2
[pip3] onnxruntime-gpu==1.1.2
Additional context
I'm using torchvision 0.5.0, because according to changelog of version 0.6.0, in 0.6.0 support of MaskRCNN export to ONNX is temporarily suspended. It has been claimed to work for version 0.5.0, or so I understand. Thanks for your help!
Hi,
Thanks for the report! This has been fixed in https://github.com/pytorch/vision/pull/2126 and https://github.com/pytorch/vision/pull/2215, and now exporting Mask R-CNN to ONNX should work on the nightly version of PyTorch and TorchVision (and a recent enough version of onnxruntime).
As such, I'm closing this issue, but let us know if you still face this issue
Hi, Thanks! Changing PyTorch and TorchVision versions enabled me to run inference correctly (finally!), but I noticed (as of today) it only works for onnxruntime version 1.2.0 and 1.3.0 - not on 1.1.2 I was previously using. Cheers
Actually, after more thorough testing I found out that after passing an image that has no detections on it, when passing a next image (no matter with or without detections) in the same inference session, an exception is thrown. Depending on the method of starting the session, the exceptions are different:
- If starting inference session with:
model = onnxruntime.backend.prepare(onnx_model_filepath, "GPU")
prediction = model.run(input_array)
The exception thrown is:
onnxruntime.capi.onnxruntime_pybind11_state.Fail: [ONNXRuntimeError] : 1 : FAIL : Non-zero status code returned while running ConvTranspose node. Name:'ConvTranspose_3164' Status Message: CUDNN error executing cudnnConvolutionBackwardData( CudnnHandle(), &alpha, s_.filter_desc, w_data, s_.x_tensor, x_data, s_.conv_desc, s_.algo, workspace.get(), s_.workspace_bytes, &beta, s_.y_tensor, y_data)
- If starting inference session with command:
session = onnxruntime.InferenceSession(onnx_model_filepath)
outputs = session.run(None, inputs)
the exception is:
onnxruntime.capi.onnxruntime_pybind11_state.Fail: [ONNXRuntimeError] : 1 : FAIL : Non-zero status code returned while running Loop node. Name:'Loop_3313' Status Message: Non-zero status code returned while running Concat node. Name:'Concat_3454' Status Message: Not satisfied: dim_value == inputs_0_dims[axis_index]
concat.cc:79 PrepareForComputeNon concat axis dimensions must match: Axis 1 has mismatched dimensions of 993 and 1024
In the latter case the error is flaky - appears some times, but not always. I think it's probably an issue for ONNX, but reporting here for future visibility.
cc @neginraoof for visibility
Thanks for reporting this.
ONNX Runtime 1.1.2 is a bit old. You can install nightly version using: pip install -i https://test.pypi.org/simple/ ort-nightly
We have a similar test here https://github.com/pytorch/vision/blob/34810c0c8e192caf29f05d7e4a02f36a9e9ebc02/test/test_onnx.py#L413 I believe ONNX Runtime 1.3.0 supports this case.
Hi, Thanks!, actually I've been following closely that unit test you mention when writing my code, it was very helpful :)
Yes, I resigned some time ago from ONNX runtime 1.1.2, and I'm using version 1.3.0 - the exceptions I posted in the above comment appeared with ONNX runtime 1.3.0, and nightly builds of Torch and Torchvision. Now, the nightly versions of ONNX runtime actually don't seem to work - the model is exported correctly (or rather: without errors), but any attempt at inference results in the following error:
onnxruntime.capi.onnxruntime_pybind11_state.RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Gather node. Name:'Gather_3011' Status Message: /onnxruntime_src/onnxruntime/core/providers/common.h:19 int64_t onnxruntime::HandleNegativeAxis(int64_t, int64_t) axis >= -tensor_rank && axis <= tensor_rank - 1 was false. axis 0 is not in valid range [-0,-1]
With stable builds of ONNX runtime v. 1.3.0, the inference works if: a) batch size is 1 at export time and inference time (otherwise inference produces senseless output), no matter if there are any detections b) batch size passed to MaskRCNN at export and batch size used at inference time is identical, and there are some detections in every image in batch // if there are no detections in the whole batch, then I'm getting the following:
[E:onnxruntime:, sequential_executor.cc:281 Execute] Non-zero status code returned while running SplitToSequence node. Name:'SplitToSequence_3577' Status Message: split_size_sum (20) != split_dim_size (0)
and if there are no detections in any image in the batch:
[E:onnxruntime:, sequential_executor.cc:281 Execute] Non-zero status code returned while running SplitToSequence node. Name:'SplitToSequence_4429' Status Message: split_size_sum (80) != split_dim_size (20)
There is also something that I discovered about dynamic_axes potentially malfunctioning. At export, I'm setting them as in the test from your repo, i.e.:
input_names=["images_tensors"],
output_names=["boxes", "labels", "scores", "masks"],
dynamic_axes={"images_tensors": [0, 1, 2, 3], "boxes": [0, 1], "labels": [0],
"scores": [0], "masks": [0, 1, 2, 3]},
This, however, results in a weird behaviour. When batch size > 1, the output array has length of batch sizex4, and is just a list of unnamed arrays of boxes, labels, scores, masks, then again boxes etc.. Interestingly, inside the onnx runtime session the output looks like in the screenshot I'm enclosing.
(This batch is a batch of 6 identical images, that's why all detections are of the same length=20).
@neginraoof or @fmassa could you please confirm that the test workflow passes for you with batch size > 1 ?
Hi, I have fixed the exceptions by setting min_size and max_size parameters at construction of MaskRCNN (I noticed it only works if difference between min_size and max_size is sufficiently small).
Still, the output looks very much like in the above screenshot - so the dynamic axis seem to be broken - only the first image's output is being parsed correctly. But with these params set, at least the model is finally usable in ONNX with a fixed batch size > 1 - even if the output needs special parsing in postprocessing. I believe this still needs fixing though.
EDIT Nope, this is still unusable. Detections are outputted only for the first image in the batch, all other outputs are always 0.
Will follow up this on the new github issue 2309.
Hi,
I am running into a similar issue, but I exported a pretrained FasterRCNN model to ONNX instead of a pretrained MaskRCNN model, and I also configured the output names and dynamic axes differently. I updated my environment to use recent torch, torchvision, and onnxruntime versions as instructed, but I still hit an almost identical exception as the one @zuzaanto reported in the 3rd repro step:
RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running ReduceMax node. Name:'ReduceMax_2080' Status Message: /onnxruntime_src/onnxruntime/core/providers/cuda/reduction/reduction_ops.cc:351 onnxruntime::common::Status onnxruntime::cuda::PrepareForReduce(onnxruntime::OpKernelContext*, bool, const std::vector<long int>&, const onnxruntime::Tensor**, onnxruntime::Tensor**, int64_t&, int64_t&, std::vector<long int>&, std::vector<long int>&, std::vector<long int>&, int64_t&, int64_t&) keepdims || dim != 0 was false. Can't reduce on dim with value of 0 if 'keepdims' is false. Invalid output shape would be produced. input_shape:{0,4}
Here is what I used to export the pretrained FasterRCNN model to ONNX:
torch.onnx.export(
model,
inputs,
onnx_model_filepath,
opset_version=11,
do_constant_folding=True,
verbose=True,
input_names=[
"input"
],
output_names=[
"boxes",
"labels",
"scores"
],
dynamic_axes={
"input": [1, 2],
"boxes": [0],
"labels": [0],
"scores": [0]
}
)
I am able to run inference without issue on an image that has objects to detect, but running inference on a random tensor results in the ReduceMax runtime exception.
Here are my environment details:
PyTorch version: 1.7.0a0+4102fbd
Is debug build: No
CUDA used to build PyTorch: 10.1
OS: Ubuntu 18.04.3 LTS
GCC version: (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
CMake version: version 3.10.2
Python version: 3.8
Is CUDA available: Yes
CUDA runtime version: 10.1.243
GPU models and configuration:
GPU 0: TITAN Xp
GPU 1: TITAN Xp
GPU 2: TITAN Xp
Nvidia driver version: 440.64.00
cuDNN version: /usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.5
Versions of relevant libraries:
[pip3] numpy==1.18.5
[pip3] torch==1.7.0a0+4102fbd
[pip3] torchvision==0.8.0a0+bea6127
[conda] magma-cuda101 2.5.2 1 pytorch
[conda] mkl 2020.1 217
[conda] mkl-include 2020.1 219 conda-forge
[conda] numpy 1.18.5 py38h8854b6b_0 conda-forge
[conda] torch 1.7.0a0+4102fbd pypi_0 pypi
[conda] torchvision 0.8.0a0+bea6127 pypi_0 pypi
!pip freeze | grep onnx
onnx==1.7.0
onnxruntime-gpu==1.3.0
I can create a new issue for this if that would be preferable since it concerns FasterRCNN instead of MaskRCNN, but I thought it was similar enough to continue the discussion from here. Thanks!
@drwaltman we replied on the other issue you created, let's keep the discussion there.
@neginraoof or @fmassa could you please confirm that the test workflow passes for you with batch size > 1 ?
@zuzaanto were you ever able to get this to work? I asked in the forums (and here too), but no luck yet.
Hi, it was quite some time ago, but I believe I did not get this to work. Eventually, I ended up giving up ONNX entirely and using TorchScript for my purpose.
I see. thanks a lot man!