When p=1, GlobalLpPool produces difference results for TensorRT and ONNXRuntime
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 13.4k
- Forks
- 2.4k
- Avg merge
- 5d 3h
- Merged PRs (30d)
- 2
Description
Description
For the following simple onnx model,
ONNXRuntime:
[array([[[[1.]],
[[1.]],
[[1.]]]], dtype=float32),
array([[[[-1.]],
[[-1.]],
[[-1.]]]], dtype=float32)]
However, when I run it using tensorrt, the results are as follows:
TensorRT:
[array([[[[-1.]],
[[-1.]],
[[-1.]]]], dtype=float32),
array([[[[-1.]],
[[-1.]],
[[-1.]]]], dtype=float32)]
In the above results, the first array is the values of 'output' and the second array is the values of ‘min_output'. From the above results, we can see that the results ‘min_output' are identical for both tensorrt and onnxruntime, while the results 'output' are different.
The reason for different 'output' may be the different calculation method in tensorrt and onnxruntime.
According to the formula of GlobalLpPool:
when p=1, the formula is as follows:
I think that onnxruntime utilizes the above formula, while tensorrt removes the Abs operation, which causes this issue.
Environment
TensorRT Version: 10.12.0.36
NVIDIA GPU: GeForce RTX 3080
NVIDIA Driver Version: 535.183.01
CUDA Version: 12.2
CUDNN Version: none
Operating System: ubuntu 20.04
Python Version (if applicable): 3.12.9
Steps To Reproduce
This issue can be reproduced by the following code with the model in the attachment.
from typing import Dict, List, Literal, Optional
import sys
import os
import numpy as np
import onnx
import onnxruntime
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
import argparse
import pickle
def test():
onnx_model = onnx.load('44.onnx')
with open("inputs.pkl", "rb") as fp:
inputs = pickle.load(fp)
try:
ort_session = onnxruntime.InferenceSession(
onnx_model.SerializeToString(), providers=["CPUExecutionProvider"]
)
ort_output = ort_session.run([], inputs)
except Exception as e:
print(e)
print("This model cannot be executed by onnxruntime!")
sys.exit(1)
print("ONNXRuntime:\n", ort_output)
#--------------------------------------------------------
trt_logger = trt.Logger(trt.Logger.WARNING)
trt.init_libnvinfer_plugins(trt_logger, '')
builder = trt.Builder(trt_logger)
network = builder.create_network(flags=1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
parser = trt.OnnxParser(network, trt_logger)
with open('44.onnx', 'rb') as model_file:
if not parser.parse(model_file.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
sys.exit(1)
config = builder.create_builder_config()
serialized_engine = builder.build_serialized_network(network, config)
if serialized_engine == None:
sys.exit(1)
with open("engine.trt", "wb") as f:
f.write(serialized_engine)
with open("engine.trt", "rb") as f, trt.Runtime(trt_logger) as runtime:
engine = runtime.deserialize_cuda_engine(f.read())
context = engine.create_execution_context()
inputs_trt, outputs_trt, bindings = [], [], []
stream = cuda.Stream()
input_name = []
output_shape_dtype = []
#------------------------------------------------------------
for binding in engine:
size = trt.volume(engine.get_tensor_shape(binding))
dtype = trt.nptype(engine.get_tensor_dtype(binding))
host_mem = cuda.pagelocked_empty(size, dtype)
device_mem = cuda.mem_alloc(host_mem.nbytes)
bindings.append({'name':binding, 'address':int(device_mem)})
if engine.get_tensor_mode(binding) == trt.TensorIOMode.INPUT:
inputs_trt.append({'host': host_mem, 'device': device_mem})
input_name.append(binding)
else:
outputs_trt.append({'host': host_mem, 'device': device_mem})
output_shape = engine.get_tensor_shape(binding)
output_shape_dtype.append({'shape':output_shape, 'dtype':dtype})
for i, input_mem in enumerate(inputs_trt):
inp = np.ravel(inputs[input_name[i]])
np.copyto(input_mem['host'], inp)
cuda.memcpy_htod_async(input_mem['device'], input_mem['host'], stream)
for bind in bindings:
name = bind['name']
addr = bind['address']
context.set_tensor_address(name, addr)
context.execute_async_v3(stream_handle=stream.handle)
trt_output = []
for i, output_mem in enumerate(outputs_trt):
cuda.memcpy_dtoh_async(output_mem['host'], output_mem['device'], stream)
out_shape = output_shape_dtype[i]['shape']
out = output_mem['host'].reshape(out_shape)
trt_output.append(out)
stream.synchronize()
print("TensorRT: \n", trt_output)
assert len(ort_output) == len(trt_output), "Unequal number of outputs"
np.testing.assert_allclose(trt_output[0], ort_output[0], rtol=0.1, atol=0.1) # BAD
if __name__ == "__main__":
test()
Commands or scripts:
Have you tried the latest release?: yes
Can this model run on other frameworks? For example run ONNX model with ONNXRuntime (polygraphy run <model.onnx> --onnxrt): the mode can be executed by onnxruntime.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied Python reproducer with 44.onnx and inputs.pkl from testcase.zip, then compare the GlobalLpPool p=1 outputs from TensorRT and ONNXRuntime. Trace the TensorRT handling of this operator and use the script's assertion to verify completion; done means the supplied case produces matching output values.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- machine-learning
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100