Repository navigation
Description
Description
Building a strongly-typed engine from an FP32 ONNX of a D-FINE (DETR-family, deformable-attention decoder) detection model on TensorRT 11.1.0.106 produces silently wrong outputs: detection scores diverge from ONNXRuntime by up to 0.15 (absolute, on sigmoid outputs) and output boxes by up to 597 px, where FP32-vs-FP32 agreement should be ~1e-4. The build completes with no warnings or errors.
The same ONNX file is exact in ONNXRuntime, and the same model executes correctly on TensorRT 10.13.3.9. On a real dataset (VisDrone test set) the mis-execution collapses recall 0.49 -> 0.34 and F1 0.587 -> 0.458.
Repo where issue was encountered - D-FINE-seg
Environment
TensorRT Version: 11.1.0.106 (tensorrt / tensorrt-cu13 wheels from PyPI)
NVIDIA GPU: GeForce RTX 5070 Ti, 16 GB (sm_120)
NVIDIA Driver Version: 580.159.03
CUDA Version: 13.0
CUDNN Version: 9.20.0.48 (not used by the repro; TRT wheels vendor their own deps)
Operating System: Ubuntu 22.04.5 LTS, kernel 6.8.0-124-generic
Python Version (if applicable): 3.13.12
Tensorflow Version (if applicable): —
PyTorch Version (if applicable): 2.12.1+cu130 (used only for CUDA buffers in the repro script; model is loaded from ONNX)
Baremetal or Container (if so, version): baremetal, pip wheels (pip install tensorrt==11.1.0.106 onnxruntime==1.21.1 onnx==1.21.0)
Relevant Files
model.onnx— D-FINE-S detection model (HGNetv2 backbone + hybrid encoder + 3-layer deformable-attention decoder + fused postprocessor), FP32, static[1,3,640,640]input, outputslabels [1,300] int64,boxes [1,300,4],scores [1,300]. Exported withtorch.onnx.export(dynamo, opset 19), simplified with onnxsim.- The bug also reproduces with a TorchScript-exporter (
dynamo=False, opset 17) export of the same weights — it is not specific to one exporter's graph flavor. repro.py— self-contained comparison script (below), deterministic synthetic input, no dataset needed.
Steps To Reproduce
Commands or scripts:
pip install tensorrt==11.1.0.106 onnxruntime==1.21.1 onnx==1.21.0 numpy torch
python repro.py model.onnx
repro.py:
import sys
import numpy as np
import onnxruntime as ort
import tensorrt as trt
import torch
onnx_path = sys.argv[1]
# deterministic structured input (gradient + rectangles, image-like, in [0,1])
rng = np.random.default_rng(0)
x = np.tile(np.linspace(0.2, 0.8, 640, dtype=np.float32)[None, :], (640, 1))
img = np.stack([x, x.T, 0.5 * (x + x.T)], 0)
for _ in range(40):
x0, y0 = rng.integers(0, 560, 2)
w, h = rng.integers(20, 80, 2)
img[:, y0 : y0 + h, x0 : x0 + w] = rng.random(3, dtype=np.float32)[:, None, None]
inp = img[None] # [1,3,640,640]
# ONNXRuntime reference
sess = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
ort_out = dict(zip([o.name for o in sess.get_outputs()], sess.run(None, {"input": inp})))
# TensorRT: strongly-typed engine from the same FP32 ONNX
logger = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(logger)
network = builder.create_network() # strongly typed (TRT >= 11 default)
parser = trt.OnnxParser(network, logger)
assert parser.parse(open(onnx_path, "rb").read())
config = builder.create_builder_config()
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 2 << 30)
engine = trt.Runtime(logger).deserialize_cuda_engine(
builder.build_serialized_network(network, config)
)
ctx = engine.create_execution_context()
bufs = {}
for i in range(engine.num_io_tensors):
name = engine.get_tensor_name(i)
shape = tuple(engine.get_tensor_shape(name))
dt = {"FLOAT": torch.float32, "INT64": torch.int64, "HALF": torch.float16}[
engine.get_tensor_dtype(name).name
]
bufs[name] = torch.empty(shape, dtype=dt, device="cuda")
ctx.set_tensor_address(name, bufs[name].data_ptr())
bufs["input"].copy_(torch.from_numpy(inp))
ctx.execute_async_v3(torch.cuda.current_stream().cuda_stream)
torch.cuda.synchronize()
for name in ("scores", "boxes"):
ref, out = ort_out[name].ravel(), bufs[name].float().cpu().numpy().ravel()
print(f"{name:7s} max_abs_diff={np.abs(ref - out).max():.4f}")
print("scores top5 ORT:", np.round(np.sort(ort_out["scores"].ravel())[::-1][:5], 4))
print("scores top5 TRT:", np.round(np.sort(bufs["scores"].float().cpu().numpy().ravel())[::-1][:5], 4))Observed output (RTX 5070 Ti, driver 580.159.03, TRT 11.1.0.106):
scores max_abs_diff=0.1495
boxes max_abs_diff=597.0000
scores top5 ORT: [0.1603 0.1174 0.0951 0.0739 0.0698]
scores top5 TRT: [0.2487 0.2349 0.2262 0.2203 0.2194]
Expected: max_abs_diff ~1e-4 or less (FP32 vs FP32). The engine builds without any warning; the wrong results are silent.
Have you tried the latest release?: Yes — 11.1.0.106 is the newest TensorRT on PyPI at the time of filing. The model executes correctly on TensorRT 10.13.3.9 (weak-typed build; FP16 engine matches the PyTorch F1 on our full benchmark).
Can this model run on other frameworks? For example run ONNX model with ONNXRuntime (polygraphy run <model.onnx> --onnxrt): Yes — ONNXRuntime (CPU EP) executes the file exactly (it is the reference in the repro). PyTorch source model agrees with ONNXRuntime.
Additional context
- The mis-execution appears tied to FP32 compilation of the transformer decoder region. Related observations on the same model, all silent:
- A mixed engine authored as FP16 backbone/encoder + FP32 decoder (explicit Cast boundaries, strongly typed) collapses the same way (dataset F1 0.587 -> 0.445), while an all-FP16 engine (only
Softmaxkept FP32) is essentially correct (F1 0.584–0.586). - Inserting FP32 islands (~100 nodes of box-decode arithmetic) into the otherwise-FP16 graph measurably degrades accuracy instead of improving it.
- With FP16 engines, accuracy differs between two ONNX graph flavors of the same weights (torch dynamo exporter 0.584 vs TorchScript exporter 0.586 dataset F1) — consistent with a graph-compilation sensitivity rather than kernel precision.
- A mixed engine authored as FP16 backbone/encoder + FP32 decoder (explicit Cast boundaries, strongly typed) collapses the same way (dataset F1 0.587 -> 0.445), while an all-FP16 engine (only
- All converted/authored ONNX variants used in these experiments execute identically to the FP32 reference in ONNXRuntime, so the divergence is introduced at TensorRT build/execution time.
Activity
whateverforever commentedon Jul 3, 2026
do you have cumsum (for example in your pos enc?) #4551
ArgoHA commentedon Jul 3, 2026
Nope
JESUSROYETH commentedon Jul 6, 2026
Hi @ArgoHA 👋
I could reproduce this on a different GPU — an RTX 4060 Laptop (Ada, sm_89), same TRT 11.1.0.106 / CUDA 13, with your
model.onnxand repro script. The strongly-typed FP32 engine diverges from ONNXRuntime by the same range you reported:So this is not specific to sm_120 / Blackwell — it shows up on Ada too, which points at a TRT 11.1 regression rather than something about your new card.
polygraphy run model.onnx --trt --onnxrtflags the same three outputs as failing, and it uses its own random inputs, so it does not depend on the exact input either.I then ran a few probes in order to narrow it down:
config.set_tactic_sources(0)(TRT-native kernels only, no cuBLAS/cuDNN) still diverges — so the bad kernel is a TRT-native tactic, not an external library.GridSamplenode with your decoder's attributes (bilinear,zeros,align_corners=0, feat[8,32,80,80], grid[8,300,3,2]) matches ORT to ~1e-5 — so the deformable-sampling op on its own is fine, the error is in the fused graph, not that op.I could not pin the exact layer yet. Marking all outputs to bisect breaks the fusions (each tensor becomes an output), and on 8 GB that either masks the bug or runs out of memory, so finding the offending tactic needs an
IAlgorithmSelectordump or a look from the TRT side.For now the only verified-correct path is staying on 10.13.3.9, as you already found. I'm happy to lock and dump the winning tactics with
IAlgorithmSelectoron the Ada repro and share which kernel flips the output, since it reproduces here.riaanmaree commentedon Jul 24, 2026
Another datapoint, which unfortunately extends this issue in two directions: we can confirm the silent wrong-results on TRT 10.16.1.11, and in our tests 10.13.3.9 is not fully clean either for a larger model of the same family.
Model: D-FINE-L (official
dfine_l_coco.pthfrom Peterande/D-FINE, exported with the repo's documentedtools/deployment/export_onnx.py, opset 16, onnxsim). The same ONNX file is used everywhere below.Environment: NVIDIA A16-16Q (Ampere vGPU, 16 GB), driver 550.90.07 / CUDA 12.4, Ubuntu 24.04,
tensorrt-cu12pip wheels. Engines built via the Python API: dynamic-batch profile (min 1 / opt 16 / max 32), 4 GiB workspace, batch 1 at runtime, 640×640. (CC 8.6 is an enumerated FP32/FP16-supported target in the 10.13/10.16 support matrix, and ORT-CUDA on this same GPU matches ORT CPU to ≤ 0.009 — so this isn't unsupported hardware or flaky silicon.)Method: 21 COCO val2017 images → 144 detections with ONNXRuntime-FP32 score ≥ 0.5 as reference; TRT outputs matched by label + IoU ≥ 0.5 (TRT candidates thresholded at 0.25 so score drops are measured rather than counted as missing). Control: ORT CPU FP32 vs ORT CUDA FP32 on the same 144 detections agrees to |Δscore|max 0.0088, |Δbox|max 1.2 px — that's the legitimate divergence floor for this graph.
Observations that line up with (and add to) the OP's wrong-tactic theory:
tensorrt-cu12<11) we got a catastrophic FP16 engine — max score 0.27, class-58 spam on every frame — plus NaN outputs at BF16 and garbage at FP32. A fresh rebuild of the same config on 10.16.1.11 instead produced the "mildly wrong" engines above. So the identical recipe lands anywhere from ~correct-looking to garbage depending on the build.So relative to the OP: we confirm correct-in-ORT / wrong-in-TRT for the D-FINE family on 10.16.x (narrowing the regression window alongside #4822's 10.14 report), but for D-FINE-L on this Ampere vGPU even 10.13.3.9 FP32 silently drops a 0.97-confidence detection — so the "10.13.3.9 is safe" workaround may be size/graph-dependent rather than general.
Happy to share the exact export/build/validation scripts and per-detection JSON diffs if useful.
ArgoHA commentedon Jul 25, 2026
yeah, it's even worse than I though. A single TensorRT inference call on a batch of four byte-identical input tensors returns four different outputs. ONNXRuntime on the same ONNX returns four identical ones.
riaanmaree commentedon Jul 25, 2026
That batch result may also explain a discrepancy between my earlier datapoint and yours, so it's worth stating the build difference explicitly.
Your repro builds a static
[1,3,640,640]network with no optimization profile. My D-FINE-L engines were built with a dynamic-batch profile (min 1 / opt 16 / max 32) and then executed at batch 1. Same ONNX, same runtime batch, different shape regime.If a single call over byte-identical rows returns different outputs per row, tactic selection is batch-sensitive — which makes "tactics timed at opt=16, executed at batch 1" exactly the configuration you'd expect to land on a kernel off its optimum. That would reconcile the two results: 10.13.3.9 static-batch-1 clean (yours), 10.13.3.9 dynamic-profile-at-batch-1 silently dropping a 0.969-confidence detection (mine), without either observation being wrong.
Two things that would sharpen your finding for triage, since it needs no reference implementation to demonstrate — TRT self-contradicts:
I can A/B static-batch-1 against dynamic-opt-16 engines from the same D-FINE-L ONNX on 10.13.3.9 and 10.16.1.11 on the Ampere vGPU if that's useful — it's a small run and it would isolate whether the shape regime, not the version, is what makes 10.13.3.9 look safe.
ArgoHA commentedon Jul 26, 2026
looks like the least wrong option is to export with min=opt=max=1. I ran tests and attach the full report
issue_4813_comment.md
ArgoHA commentedon Jul 26, 2026
https://drive.google.com/file/d/1A2qlRlozHEEAnqR2uXUYPpF4b67R-sXC/view?usp=share_link
riaanmaree commentedon Jul 26, 2026
Thanks for running both probes — that answers it, and it refutes the mechanism I proposed, so let me retract that part explicitly rather than leave it in the thread for someone to triage against.
What I got wrong. "Tactics timed at opt, executed elsewhere" is dead. Your §3 kills it:
optis 1 in that engine, so batch 1 is the timed shape, and it is the worst configuration measured — while the same engine at batch 4 returns row 0 with zero losses. A mistimed tactic also can't produce four different answers for four identical rows, since one tactic processes the whole batch. Your slot-determinism result (bit-identical per slot across 50 repeats, a freshIExecutionContextand a fresh deserialize) points somewhere quite different: a fused kernel reading or writing across batch stride, fixed at build time. That the leak runs in both directions — other rows' contents moving slot 0 by 0.0015–0.0020 — is hard to read any other way.What survives. The profile width result (
max1→ 3 lost,max4→ 12 lost, both executed at batch 1, identical builder config, reproduced on a second build pair) does reconcile the discrepancy between your clean 10.13.3.9 and my 10.13.3.9 dropping a 0.969-confidence detection: mine were built on a min 1 / opt 16 / max 32 profile. So my 24 Jul table should be read as evidence about the dynamic-profile regime, not about the version alone, and I've recorded it that way on my side. The version axis in it still stands on its own — 10.16.1.11 FP32 loses 6 of 144 where 10.13.3.9 FP32 loses 1, same profile, same ONNX, same GPU.On the segmentation video. I pulled it and measured it frame by frame, since a video is easy to under-read. Cropping the header/footer bars and counting pane pixels differing by more than 25 grey levels (the panes are exactly aligned — mean difference 1.03% at shift 0 against 2.67% at ±1 px), 120 of the 357 frames diverge over 0.5% of the pane, 54 over 2%, and 18 over 5%. Worst is frame 244 at t ≈ 14.3 s, 9.9% of pixels, 18 instances against 16: the batch-4 stream drops the car directly ahead in the ego lane and the large vehicle at close range on the right — the two nearest objects in the frame. Same shape at t ≈ 5 s, 7 against 5. Meanwhile t ≈ 10 s and t ≈ 20 s agree exactly, 20/20 and 15/15. That intermittency is the part I'd want a maintainer to see: it is not a constant offset you could calibrate around, and it removes the closest objects in the scene. (I left sub-0.5% differences uncounted — the video is H.264, so mask-edge noise there isn't separable from codec noise.)
It also shows the defect isn't confined to the detection head — it reproduces on the instance-segmentation variant of the same family, on 10.13.3.9.
Three things worth flagging for anyone who lands here to decide whether they're affected, because the practical shape of this is nastier than "use static shapes":
max4engine is worse at batch 1 (12 lost) than at batch 4 slot 0 (0 lost). In the segmentation video, batch 4 is the pane that loses the nearest vehicles. Both on 10.13.3.9. Nothing about that is guessable from the config; it has to be measured per (profile, executed batch, slot, model).min=opt=max=1is a throughput decision, not just a build flag. N independent batch-1 engine instances means N× weights resident, which on a small-vRAM card is the difference between deployable and not. Anyone whose reason for using TRT was batching is choosing between the accuracy and the reason they came.Between the four reports the thread now covers sm_120, Ada sm_89 and an Ampere vGPU; D-FINE-S and D-FINE-L; and TRT 10.13.3.9, 10.16.1.11 and 11.1.0.106 — all correct in ONNXRuntime, all wrong in TensorRT, deterministically and on the same detections.
@ArgoHA's batch probe is the cheapest possible entry point for triage: it needs no reference implementation and no dataset, because TensorRT contradicts itself within a single call — four byte-identical rows in, four different answers out, reproducibly at the same slot.rahuldeepak-the-one commentedon Aug 2, 2026
I hit what looks like the same thing on TRT 10.14.1.48, sm_86, with a DEIMv2 model (DEIM
family, so the same deformable-attention decoder lineage as D-FINE). Posting because a couple of
my results cut against where the thread has landed, and because I have a workaround that isn't
"downgrade" or "give up batching".
It's a customer model, so I can't share the weights or the footage. The graph-surgery script is
at the bottom of this comment, and I can post the per-detection numbers behind the table if
anyone wants them.
Setup: 640×640, FP32, opset 16 from PyTorch 2.5.1, 12 GridSample ops across 4 decoder layers.
Engine built through the Python API, weakly typed, no FP16/INT8 flags, profile pinned with
set_shape(name, s, s, s)at(1,3,640,640). Three arms over 1220 frames — ORT on the originalgraph as reference, TRT on that same graph, and TRT after rewriting the deformable attention to
MultiscaleDeformableAttnPlugin_TRT. Same TRT version and builder config for both engines, sothe rewrite is the only variable between rows two and three:
The bad engine also emits five categories the ONNX never produces at all, and the dominant class
drops from 4880 instances to 929.
Same signature you've both described — boxes correct to about a pixel, all the damage in the
classification scores. Things I chased before suspecting the runtime, none of which were the
cause: preprocessing and letterboxing, the score threshold, and TF32 (rebuilt with
NVIDIA_TF32_OVERRIDE=0, no change). At a 0.4 threshold this silently drops two thirds of thereal objects while every surviving box sits exactly where it should, so on an overlay it just
looks like a model having a bad day.
Two things that don't fit the current picture.
min=opt=max=1didn't help — that pinned profileis the configuration in the table, and it's the catastrophic case rather than a least-wrong
one. The same model at dynamic batch 4 under DeepStream nvinfer is equally broken, so on 10.14
both shape regimes fail. And #4822 reports 10.14 too but found sm_86 correct for their model,
where I'm broken on sm_86 — so immunity doesn't seem to carry from one graph to another.
The workaround is the script below. It rewrites each decoder layer's GridSample-decomposed
deformable attention into a single
MultiscaleDeformableAttnPlugin_TRTnode withonnx-graphsurgeon (12 GridSample ops to 0); build the engine from that graph instead. The plugin
ships inside TensorRT so there's nothing to install, though
trt.init_libnvinfer_plugins(logger, "")is needed to build and load. It auto-detects the layer count, derives the feature-level sizes
from the input resolution, and no-ops if the graph doesn't match. It restores parity rather than
reducing the damage — the dominant class matches ORT exactly at 4880 — and it keeps batching, so
no N× resident weights for N batch-1 engines.
Limits: it only helps if the fault is in this subgraph, so no use for something like #4822's
FastConformer, and ORT can't run the rewritten graph afterwards because of the plugin node — keep
the original as your reference.
Possibly a triage clue too. It fits @JESUSROYETH's probe 3,an isolated GridSample node matching
ORT to ~1e-5 means the op is fine and the fusion around it isn't. Making just that subgraph
opaque to the fuser fixes the whole model, which puts the fault inside the deformable-attention
region, and fits the batch-stride theory since the plugin does its own batch indexing.
msda_surgery.py— GridSample deformable-attn → MSDA pluginThe tensor names it matches (
cross_attn/Add_output_0,Softmax_output_0,Transpose_2_output_0) are what the standard deformable-DETR decoder export produces, so itshould apply to D-FINE with little or no change.
Happy to run more on sm_86 / 10.14 — @ArgoHA's byte-identical-batch test on this graph, or an
IAlgorithmSelectordump across the two builds to try to name the kernel that differs. Notrtexec or polygraphy in my container, so Python API only.
kvnloo commentedon Sep 28, 2026
The new SM86 DEIMv2 datapoint seems important because it shows this is not only a Blackwell/TRT-11 strongly-typed issue.
On TensorRT 10.14.1 +
sm_86, the original deformable-attention graph is badly wrong while rewriting toMultiscaleDeformableAttnPlugin_TRTnearly restores the ONNX Runtime result.That makes the next comparison quite focused:
I have an RTX 3080 Ti (
sm_86) available and can help reproduce this class locally.I would also capture batch/profile width, since this thread has strong evidence that wider profiles change the error even at batch 1.
If the plugin arm stays correct while the native graph fails, we can progressively reduce only the deformable-attention subgraph rather than the entire DETR model.
kleinicke commentedon Nov 13, 2026
Another datapoint, TensorRT 11.4.0.106 on an RTX 5060 Ti (sm_120): D-FINE-X (official COCO weights, 640x640), ONNX from the torch 2.14.1 dynamo exporter (opset 18, fp16 weights), strongly typed network, static shape, default config. The engine builds in 57 s without a warning and returns NaN for every element of both outputs:
onnxruntime 1.32.0 (CPU) on the same file and input gives finite outputs in the same range as PyTorch (logits -8.3..-0.9, boxes -0.12..1.01, top score 0.288 vs 0.295 in eager). The fp32 export of the same model builds (41 s) and gives finite but wrong outputs: top score 0.186 where onnxruntime and PyTorch both give 0.291, the boxes of the top-10 detections differ by up to 0.70 (normalized coordinates) from the nearest reference box, and the labels do not agree (label agreement 0.00); onnxruntime fp32 matches PyTorch fp32 (same top score, median box error 0.000). The S, M and L variants of the same export build and give correct detections; only X fails. The largest activation in the PyTorch fp16 forward is about 150, so this is not an fp16 overflow in the model itself.
Environment: TensorRT 11.4.0.106, RTX 5060 Ti 16 GB (sm_120), driver 595.99.02, CUDA 13.0, Ubuntu 26.04, Python 3.12, onnx 1.23.2, onnxruntime 1.32.0. Build:
trt.Builder+OnnxParser.parse_from_filewithNetworkDefinitionCreationFlag.STRONGLY_TYPEDandcreate_builder_config()unchanged.The ONNX file is 123 MB (Apache-2.0), above the attachment limit; I can share it on request.
ArgoHA commentedon Nov 15, 2026
I ended up implementing a workaround in D-FINE-seg export. I dropped GridSample and used an equivalent bilinear sampling built from four row-gathers per level. TensorRT now matches PyTorch and the batch slot issue is also resolved. I made sure to have 0 latency overheads. Tested for all tasks (detection, keypoints, instance and semantic segmentation)
shoumikhin commentedon Nov 16, 2026
Another datapoint, on a datacenter GPU and the newest TensorRT, with a repro that needs no shared files: D-FINE L from the public Hugging Face checkpoint
ustc-community/dfine-large-obj2coco-e25, exported to ONNX (opset 17) and built with the plain TensorRT Python API.Setup: H100 (sm_90), TensorRT 11.4.0.106, torch 2.15.0, strongly typed network, TF32 flag cleared, static
[1,3,640,640], seeded random input.Result (class logits, mean abs diff and top-1 class agreement):
So the TensorRT error is the size of a TF32-level precision loss, not fp32 rounding. It is the same at builder optimization level 0 and 3, and TensorRT 10.16.1.11 gives 0.47 on the same ONNX.
Where it starts, from a bisect of the same graph:
So it looks like one kernel that is picked only for the fused whole graph, right after decoder layer 0 (layer 0's box refinement, or layer 1's sampling at the refined points). That fits the earlier finding here that replacing GridSample with gathers fixes it.
Repro (
python repro.py CHECKPOINT_DIR OUT_DIR):