Repository navigation
Description
Description
TensorRT 11.5.0.63 (Python tensorrt==11.5.0.63, tensorrt_cu12) builds and runs an ONNX ScatterElements (opset 18, axis=1, default reduction=none) engine, but the output disagrees with PyTorch Tensor.scatter whenever the index tensor contains duplicates along the scatter axis.
With unique indices, TensorRT matches PyTorch exactly (max_abs=0). With duplicates, TensorRT keeps the first update written along that axis (first-write-wins). PyTorch CPU applies last-write-wins.
A 2×3 example (GPU A40):
index = [[0, 0, 2],
[1, 1, 2]]
data = [[10, 20, 30],
[40, 50, 60]]
updates = [[ 1, 2, 3],
[ 4, 5, 6]]
PyTorch (last-write-wins): [[2, 20, 3],
[40, 5, 6]]
TensorRT 11.5.0 (first-write-wins): [[1, 20, 3],
[40, 4, 6]]
TRT vs torch max_abs = 1.0
No TensorRT “indices are not duplicated” warning was observed on this ScatterElements path (unlike the documented ScatterND warning).
ONNX ScatterElements with reduction=none states that the result is undefined if indices are not unique. If TensorRT intentionally uses a first-write or unordered reduction, please document that and emit a build/runtime warning for ScatterElements comparable to ScatterND. If last-write-wins (matching PyTorch Tensor.scatter) is intended, this is a correctness bug. Unique-index models are already correct.
Related, not duplicates:
- TensorRT engine execution return all 0 due to warning[ScatterND with reduction==‘none’ only guarantees to be correct if indices are not duplicated.] #4425 — ScatterND, engine output all zeros, plus warning
ScatterND with reduction=='none' only guarantees to be correct if indices are not duplicated. Different op and symptom. - ScatterND in a dynamic-shape engine silently drops updates beyond ~N when the update count M exceeds the output size N (static engine correct) #4861 — ScatterND in a dynamic-shape engine silently drops updates when
M > N. Different failure mode; the reduced repro here is static 2×3.
Environment
TensorRT Version: 11.5.0.63 (Python package tensorrt==11.5.0.63 / tensorrt_cu12)
NVIDIA GPU: NVIDIA A40 (device 0)
NVIDIA Driver Version: 550.54.14
CUDA Version: toolkit 12.4 (libcudart 12.4). Engine is executed via system libcudart.so.12.
CUDNN Version: 9.0.0 (libcudnn.so.9.0.0)
Operating System: Ubuntu 22.04.5 LTS (x86_64), glibc 2.35
Python Version (if applicable): 3.11.17
Tensorflow Version (if applicable): N/A
PyTorch Version (if applicable): 2.14.0+cpu (used as a numeric oracle and to fill host buffers). CUDA is not available in this torch wheel.
Baremetal or Container (if so, version): baremetal
Relevant Files
Model link: The script below writes a tiny ONNX model (scatter_2x3_onedup.onnx) at runtime. No external weights are required.
Steps To Reproduce
The script builds a one-node ONNX ScatterElements model, runs it with TensorRT 11.5 on GPU, and compares against torch.Tensor.scatter. It uses libcudart.so.12 via ctypes (no pycuda / polygraphy required).
Commands or scripts:
python repro_trt_scatter_elements.py#!/usr/bin/env python3
import ctypes
import numpy as np
import torch
import onnx
from onnx import helper, numpy_helper, TensorProto
import tensorrt as trt
data = np.array([[10.0, 20.0, 30.0],
[40.0, 50.0, 60.0]], dtype=np.float32)
index = np.array([[0, 0, 2],
[1, 1, 2]], dtype=np.int64)
updates = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]], dtype=np.float32)
def save_onnx(path):
n = helper.make_node("ScatterElements", ["data", "index", "updates"], ["Y"], axis=1)
g = helper.make_graph(
[n], "g",
[helper.make_tensor_value_info("data", TensorProto.FLOAT, [2, 3]),
helper.make_tensor_value_info("updates", TensorProto.FLOAT, [2, 3])],
[helper.make_tensor_value_info("Y", TensorProto.FLOAT, [2, 3])],
initializer=[numpy_helper.from_array(index, "index")],
)
onnx.save(helper.make_model(g, opset_imports=[helper.make_opsetid("", 18)], ir_version=10), path)
# --- TensorRT + cudart ---
H2D, D2H = 1, 2
cudart = ctypes.CDLL("libcudart.so.12")
cudart.cudaMalloc.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t]
cudart.cudaMalloc.restype = cudart.cudaFree.restype = ctypes.c_int
cudart.cudaFree.argtypes = [ctypes.c_void_p]
cudart.cudaMemcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]
cudart.cudaMemcpy.restype = ctypes.c_int
cudart.cudaStreamCreate.argtypes = [ctypes.POINTER(ctypes.c_void_p)]
cudart.cudaStreamCreate.restype = ctypes.c_int
cudart.cudaStreamSynchronize.argtypes = [ctypes.c_void_p]
cudart.cudaStreamSynchronize.restype = ctypes.c_int
def ck(err, what):
if int(err) != 0:
raise RuntimeError(f"{what}: cudaError={err}")
def trt_run(path, feeds):
logger = trt.Logger(trt.Logger.WARNING)
with open(path, "rb") as f, trt.Builder(logger) as builder:
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
| 1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
parser = trt.OnnxParser(network, logger)
if not parser.parse(f.read()):
raise RuntimeError("parse failed: " + "; ".join(str(parser.get_error(i)) for i in range(parser.num_errors)))
config = builder.create_builder_config()
engine = builder.build_serialized_network(network, config)
if engine is None:
raise RuntimeError("build_serialized_network returned None")
runtime = trt.Runtime(logger)
eng = runtime.deserialize_cuda_engine(engine)
ctx = eng.create_execution_context()
stream = ctypes.c_void_p()
ck(cudart.cudaStreamCreate(ctypes.byref(stream)), "stream")
ptrs = []
def malloc_and_set(name, host, copy_in):
p = ctypes.c_void_p()
ck(cudart.cudaMalloc(ctypes.byref(p), max(host.nbytes, 1)), name)
ptrs.append(p)
if copy_in and host.nbytes:
ck(cudart.cudaMemcpy(p, ctypes.c_void_p(host.ctypes.data), host.nbytes, H2D), "H2D")
if not ctx.set_tensor_address(name, int(p.value)):
raise RuntimeError(f"set_tensor_address {name}")
return p
for i in range(eng.num_io_tensors):
name = eng.get_tensor_name(i)
mode = eng.get_tensor_mode(name)
if mode == trt.TensorIOMode.INPUT:
malloc_and_set(name, np.ascontiguousarray(feeds[name]), True)
else:
shape = tuple(int(s) for s in ctx.get_tensor_shape(name))
host = np.empty(shape, dtype=np.float32)
malloc_and_set(name, host, False)
out_host, out_ptr, out_name = host, ptrs[-1], name
if not ctx.execute_async_v3(int(stream.value)):
raise RuntimeError("execute_async_v3 failed")
ck(cudart.cudaStreamSynchronize(stream), "sync")
ck(cudart.cudaMemcpy(ctypes.c_void_p(out_host.ctypes.data), out_ptr, out_host.nbytes, D2H), "D2H")
for p in ptrs:
cudart.cudaFree(p)
return out_host.copy()
if __name__ == "__main__":
path = "scatter_2x3_onedup.onnx"
save_onnx(path)
y_torch = torch.from_numpy(data.copy()).scatter(1, torch.from_numpy(index), torch.from_numpy(updates)).numpy()
y_trt = trt_run(path, {"data": data, "updates": updates})
print("torch\n", y_torch)
print("TRT \n", y_trt, "match torch", np.array_equal(y_trt, y_torch))
print("TRT-torch max_abs", float(np.max(np.abs(y_trt - y_torch))))If build_serialized_network returns None because of strongly-typed network flags on a given wheel, drop STRONGLY_TYPED and (if the builder requires it) add an optimization profile with min=opt=max=(2,3) for data and updates. On this machine the 2×3 case produced the numbers above.
Activity