Skip to content

TRT 11.1 strongly-typed FP32 engine silently produces wrong results for a DETR-style detection model (correct in ONNXRuntime and TRT 10.13) #4813

Open

Description

@ArgoHA

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 link: https://drive.google.com/file/d/1Fs6nh2Edv1-1xFbqnIN5zTvE4nzfe7Ta/view?usp=share_link

  • 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, outputs labels [1,300] int64, boxes [1,300,4], scores [1,300]. Exported with torch.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 Softmax kept 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.
  • 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

  1. added
    Module:Accuracy
    on Jul 1, 2026
  2. whateverforever commented on Jul 3, 2026

    @whateverforever

    do you have cumsum (for example in your pos enc?) #4551

  3. ArgoHA commented on Jul 3, 2026

    @ArgoHA
    Author

    Nope

  4. JESUSROYETH commented on Jul 6, 2026

    @JESUSROYETH

    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.onnx and repro script. The strongly-typed FP32 engine diverges from ONNXRuntime by the same range you reported:

    scores  max|Δ| = 0.196
    boxes   max|Δ| = 605 px
    labels  differ by up to 9
    

    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 --onnxrt flags 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:

    1. Weakly-typed FP32 network (the legacy default) also diverges — so turning off strong typing is not a workaround, and the strongly-typed path is not really the cause.
    2. 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.
    3. A single GridSample node 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.
    4. The magnitude changes a bit from run to run, which fits a tactic-selection problem: a specific fused kernel returns wrong values and gets picked during timing.

    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 IAlgorithmSelector dump 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 IAlgorithmSelector on the Ada repro and share which kernel flips the output, since it reproduces here.

  5. riaanmaree commented on Jul 24, 2026

    @riaanmaree

    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.pth from Peterande/D-FINE, exported with the repo's documented tools/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-cu12 pip 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.

    Backend matched Δscore p95 Δscore max Δbox max silently lost (ref score)
    ORT CPU vs CUDA (control) 144/144 0.003 0.009 1.2 px —
    TRT 10.13.3.9 FP16 144/144 0.039 0.441 11.2 px 0
    TRT 10.13.3.9 FP32 143/144 0.052 0.386 10.9 px 1 (0.969)
    TRT 10.16.1.11 FP16 144/144 0.039 0.439 10.7 px 0
    TRT 10.16.1.11 FP32 138/144 0.063 0.552 22.7 px 6 (0.97, 0.96, 0.96, 0.92, 0.72, 0.59)

    Observations that line up with (and add to) the OP's wrong-tactic theory:

    • The same detections fail on every engine. E.g. one object at ref score 0.961 comes out at 0.52 / 0.575 / 0.522 on three engines and disappears entirely on the fourth; another (ref 0.969→0.704 region) is wrong on both FP32 engines. Deterministic per-input, across versions and precisions.
    • FP32 is worse than FP16 on both versions (more silent losses, larger drift) — hard to explain by numerics, consistent with fusion/tactic selection.
    • Build-to-build nondeterminism in failure severity: in an earlier round (same export path, same builder config, 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.
    • Single-frame checks are misleading: our 10.13.3.9 FP16 engine passes a 5-detection street scene within FP16 tolerance (Δscore ≤ 0.045), and only the multi-image set exposes the 0.44 worst case.

    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.

  6. ArgoHA commented on Jul 25, 2026

    @ArgoHA
    Author

    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.

  7. riaanmaree commented on Jul 25, 2026

    @riaanmaree

    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:

    1. Was that engine static-shape or built with an optimization profile? If dynamic, does the opt batch value change the outcome?
    2. Is the divergence tied to row position (row k consistently wrong across runs) or run-to-run noise? Position-dependence points at a fused kernel indexing off batch stride; run-to-run points back at tactic timing.

    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.

  8. ArgoHA commented on Jul 26, 2026

    @ArgoHA
    Author

    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

  9. riaanmaree commented on Jul 26, 2026

    @riaanmaree

    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: opt is 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 fresh IExecutionContext and 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":

    1. Accuracy is non-monotonic in batch, and the sign isn't even stable across your own two artefacts, so "just lower the batch size" is not a safe mitigation. In the detection probe the max4 engine 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).
    2. min=opt=max=1 is 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.
    3. A smoke test will not catch this, in either of our setups. Your ≥ 0.50 band shows max |Δbox| 1.0 px and zero label differences — the geometry looks perfect; the damage is entirely in the score, silently removing high-confidence detections at a fixed threshold. On my side, a 5-detection single-frame check passed within FP16 tolerance while the multi-image set exposed the 0.44 worst case. Anyone adopting the static-engine workaround needs a matched multi-image accuracy gate against ORT, not a visual check — and per your own numbers it is least-wrong rather than correct: 3–4 detections ≥ 0.90 lost out of 5,109 at p95 Δscore 0.044, against a legitimate ORT CPU-vs-CUDA floor that measured ≤ 0.009 on my graph.

    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.

  10. rahuldeepak-the-one commented on Aug 2, 2026

    @rahuldeepak-the-one

    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 original
    graph 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, so
    the rewrite is the only variable between rows two and three:

    arm detections persons mean conf frames agreeing with ORT on person count
    ONNX Runtime 6269 1376 0.9364 —
    TRT, original graph 1481 468 0.6310 28.9 %
    TRT, MSDA plugin 6256 1362 0.9345 98.7 %

    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 the
    real 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=1 didn't help — that pinned profile
    is 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_TRT node with
    onnx-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 plugin
    #!/usr/bin/env python3
    """Replace a DEIM/DETR ONNX's GridSample-decomposed multi-scale deformable attention
    (which TRT 10.14 miscompiles -> corrupted class logits -> wrong/dropped detections)
    with NVIDIA's MultiscaleDeformableAttnPlugin_TRT, whose CUDA bilinear kernel matches the
    pytorch/ORT reference. One plugin node per decoder layer.
    
    GENERIC: works for any DEIM-arch export that uses the standard deformable-DETR decoder
    naming (`/decoder/decoder/layers.<L>/cross_attn/...` + a shared `/decoder/decoder/
    Transpose_output_0` value tensor) — verified on two independently trained DEIM-arch models.
    - decoder layer count is auto-detected (not hardcoded)
    - feature-level grid sizes are derived from the network input H/W (H/8, H/16, H/32)
    - SELF-DETECTING + SAFE no-op: if the graph has no GridSample deformable-attn pattern
      (e.g. a YOLO/CNN onnx, or an already-surgered graph) it copies the input through
      unchanged and exits 0, so it is safe to run unconditionally on any .onnx.
    """
    import os, re, sys, shutil, numpy as np, onnx
    import onnx_graphsurgeon as gs
    
    # MSDA_STATIC=0 (default) keeps dynamic batch → one surgered onnx builds b1/b4/bN engines.
    # MSDA_STATIC=1 pins batch to 1, only for standalone single-image ORT/TRT verification.
    PIN_STATIC = os.environ.get("MSDA_STATIC", "0") == "1"
    NUM_LEVELS, NUM_POINTS = 3, 4   # standard deformable-DETR: 3 feature scales, 4 points/level
    
    SRC = sys.argv[1] if len(sys.argv) > 1 else "model.onnx"
    DST = sys.argv[2] if len(sys.argv) > 2 else "model_msda.onnx"
    
    VALUE_SRC = "/decoder/decoder/Transpose_output_0"   # (bs,heads,dim,keys) shared value, all layers
    LAYER_RE  = re.compile(r"/decoder/decoder/layers\.(\d+)/cross_attn/")
    
    
    def _passthrough(reason):
        """Not a (surgerable) DEIM deformable-attn graph — leave the onnx unchanged."""
        print(f"[msda_surgery] no-op ({reason}); onnx left unchanged")
        if os.path.abspath(SRC) != os.path.abspath(DST):
            shutil.copyfile(SRC, DST)
        sys.exit(0)
    
    
    g = gs.import_onnx(onnx.load(SRC))
    
    # ── Detection gate: is this a DEIM/DETR deformable-attn graph we can surger? ──
    have_gridsample = any(n.op == "GridSample" for n in g.nodes)
    layers = sorted({int(m.group(1)) for n in g.nodes
                     if (m := LAYER_RE.search(n.name or ""))})
    t = g.tensors()
    if not have_gridsample or not layers or VALUE_SRC not in t:
        _passthrough("no GridSample / cross_attn decoder layers / value tensor")
    
    # ── Network input H/W → per-level grid sizes (P3/P4/P5 = stride 8/16/32) ──
    H = W = 640
    for inp in g.inputs:
        if inp.name == "images" and inp.shape and len(inp.shape) == 4:
            h, w = inp.shape[2], inp.shape[3]
            if isinstance(h, int) and isinstance(w, int) and h > 0 and w > 0:
                H, W = h, w
    LEVELS = [(H // 8, W // 8), (H // 16, W // 16), (H // 32, W // 32)]
    sizes = [h * w for h, w in LEVELS]
    start = [0]
    for s in sizes[:-1]:
        start.append(start[-1] + s)
    print(f"[msda_surgery] DEIM graph: {len(layers)} decoder layer(s) {layers}, "
          f"input {H}x{W}, levels {LEVELS}")
    
    # Pin input to static [1,3,H,W] so the plugin's output extent is concrete at parse time
    # (getOutputDimensions can't resolve through a symbolic batch dim -> breaks the downstream
    # gateway/Concat extent computation).
    if PIN_STATIC:
        for inp in g.inputs:
            if inp.name == "images":
                inp.shape = [1, 3, H, W]
    
    # shared constants
    spatial_shapes = gs.Constant("msda_spatial_shapes", np.array(LEVELS, dtype=np.int32))
    level_start    = gs.Constant("msda_level_start_index", np.array(start, dtype=np.int32))
    
    # shared value transpose -> [bs, keys, heads, dim]
    value_t = gs.Variable("msda_value", dtype=np.float32)
    g.nodes.append(gs.Node("Transpose", "msda_value_transpose",
                           attrs={"perm": [0, 3, 1, 2]},
                           inputs=[t[VALUE_SRC]], outputs=[value_t]))
    
    samp_shape = gs.Constant("msda_samp_shape", np.array([0, 0, 0, NUM_LEVELS, NUM_POINTS, 2], np.int64))
    attn_shape = gs.Constant("msda_attn_shape", np.array([0, 0, 0, NUM_LEVELS, NUM_POINTS], np.int64))
    # plugin v1 outputs [bs, num_query, num_heads, channels]; flatten last two -> [bs, num_query, embed]
    flat_shape = gs.Constant("msda_flat_shape", np.array([0, 0, -1], np.int64))
    
    for L in layers:
        p = f"/decoder/decoder/layers.{L}/cross_attn/"
        try:
            samp_src = t[p + "Add_output_0"]        # (bs,Q,heads,levels*points,2) sampling_locations in [0,1]
            attn_src = t[p + "Softmax_output_0"]    # (bs,Q,heads,levels*points) attention weights
            out_t    = t[p + "Transpose_2_output_0"]  # (bs,Q,embed) cross-attn output to replace
        except KeyError as e:
            _passthrough(f"layer {L} missing expected tensor {e}")
        out_t.inputs.clear()                        # detach old GridSample producer
    
        samp = gs.Variable(f"msda_samp_{L}", dtype=np.float32)
        attn = gs.Variable(f"msda_attn_{L}", dtype=np.float32)
        g.nodes.append(gs.Node("Reshape", f"msda_reshape_samp_{L}",
                               inputs=[samp_src, samp_shape], outputs=[samp]))
        g.nodes.append(gs.Node("Reshape", f"msda_reshape_attn_{L}",
                               inputs=[attn_src, attn_shape], outputs=[attn]))
        plug_out = gs.Variable(f"msda_out_{L}", dtype=np.float32)
        g.nodes.append(gs.Node(
            "MultiscaleDeformableAttnPlugin_TRT", f"msda_plugin_{L}",
            inputs=[value_t, spatial_shapes, level_start, samp, attn],
            outputs=[plug_out]))
        g.nodes.append(gs.Node("Reshape", f"msda_flatten_{L}",
                               inputs=[plug_out, flat_shape], outputs=[out_t]))
    
    g.cleanup().toposort()
    m = gs.export_onnx(g)
    onnx.save(m, DST)
    print(f"[msda_surgery] wrote {DST} ({len(layers)} MSDA plugin node(s))")

    The 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 it
    should 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
    IAlgorithmSelector dump across the two builds to try to name the kernel that differs. No
    trtexec or polygraphy in my container, so Python API only.

  11. kvnloo commented on Sep 28, 2026

    @kvnloo

    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 to MultiscaleDeformableAttnPlugin_TRT nearly restores the ONNX Runtime result.

    That makes the next comparison quite focused:

    • same checkpoint/inputs;
    • original GridSample-based deformable-attention graph;
    • MSDA plugin rewrite;
    • same TensorRT version/build/profile.

    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.

  12. kleinicke commented on Nov 13, 2026

    @kleinicke

    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:

    output logits (1, 300, 80) float32: nan fraction 1.000
    output boxes (1, 300, 4) float32: nan fraction 1.000
    

    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_file with NetworkDefinitionCreationFlag.STRONGLY_TYPED and create_builder_config() unchanged.

    The ONNX file is 123 MB (Apache-2.0), above the attachment limit; I can share it on request.

  13. ArgoHA commented on Nov 15, 2026

    @ArgoHA
    Author

    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)

  14. shoumikhin commented on Nov 16, 2026

    @shoumikhin

    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):

    comparison mean abs diff top-1 agreement
    eager fp32 vs eager fp64 1.3e-5 100%
    eager TF32 vs eager fp32 (for scale) 0.57 56%
    TensorRT fp32 vs eager fp32 0.51 63%

    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:

    • Exact (1e-5 or better) when any one of grid_sample, gather or topk runs outside the engine, so the graph is split.
    • Exact when each grid_sample, one deformable attention block, or the whole decoder is built alone.
    • In the full engine with intermediate outputs marked: encoder outputs, top-k query logits and initial reference points are exact, decoder layer 0 is at 1e-6, and layers 1 to 5 are at 0.13 to 0.16.

    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):

    import json
    import os
    import sys
    
    import tensorrt as trt
    import torch
    from transformers import AutoModelForObjectDetection
    
    
    class Net(torch.nn.Module):
        def __init__(self, model):
            super().__init__()
            self.model = model
    
        def forward(self, pixels):
            out = self.model(pixel_values=pixels)
            return out.logits, out.pred_boxes
    
    
    def diff(a, b):
        return {"logits_mean_abs_diff": float((a[0] - b[0]).abs().mean()),
                "top1_class_agreement": float((a[0].argmax(-1) == b[0].argmax(-1)).float().mean())}
    
    
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False
    os.makedirs(sys.argv[2], exist_ok=True)
    onnx_path = os.path.join(sys.argv[2], "dfine_l.onnx")
    net = Net(AutoModelForObjectDetection.from_pretrained(sys.argv[1], dtype=torch.float32)).cuda().eval()
    x = torch.rand(1, 3, 640, 640, generator=torch.Generator().manual_seed(0)).cuda()
    with torch.no_grad():
        ref = net(x)
        ref64 = [t.float() for t in net.double()(x.double())]
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.allow_tf32 = True
        tf32 = net.float()(x)
        torch.backends.cuda.matmul.allow_tf32 = False
        torch.backends.cudnn.allow_tf32 = False
        torch.onnx.export(net, (x,), onnx_path, opset_version=17, dynamo=False, input_names=["pixels"],
                          output_names=["logits", "boxes"])
    
    logger = trt.Logger(trt.Logger.WARNING)
    builder = trt.Builder(logger)
    network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
    parser = trt.OnnxParser(network, logger)
    assert parser.parse_from_file(onnx_path), [str(parser.get_error(i)) for i in range(parser.num_errors)]
    config = builder.create_builder_config()
    config.clear_flag(trt.BuilderFlag.TF32)
    engine = trt.Runtime(logger).deserialize_cuda_engine(builder.build_serialized_network(network, config))
    ctx = engine.create_execution_context()
    out = [torch.empty(tuple(engine.get_tensor_shape(n)), device="cuda") for n in ("logits", "boxes")]
    ctx.set_tensor_address("pixels", x.data_ptr())
    for n, t in zip(("logits", "boxes"), out):
        ctx.set_tensor_address(n, t.data_ptr())
    ctx.execute_async_v3(torch.cuda.current_stream().cuda_stream)
    torch.cuda.synchronize()
    print(json.dumps({"torch": torch.__version__, "tensorrt": trt.__version__,
                      "eager_fp32_vs_fp64": diff(ref, ref64), "eager_tf32_vs_fp32": diff(tf32, ref),
                      "tensorrt_fp32_vs_eager_fp32": diff(out, ref)}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Module:Accuracy

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions