[Tracker] ONNX bugs worked around in transformers.exporters
transformers.exporters exports π€ Transformers models to ONNX, working around each bug below with a patch on our side. This issue tracks them until they're fixed upstream, in justinchuby/torch-onnx (the standalone PyTorch ONNX exporter): each item is reproduced without transformers, in a minimal script, on torch 2.15.0, onnxscript 0.7.2, onnx 1.23.2, onnxruntime 1.32.0 (CPU), Python 3.11. Every fix brings π€ Transformers models closer to running in the browser, on Windows and on mobile, through ONNX Runtime.
Every item below breaks the export of real π€ Transformers models, listed under it: none is a hypothetical edge case.
This tracker is for people making their first contributions to large open-source projects. Each item is a small, self-contained bug with a minimal repro, and its fix gets you merged upstream and in transformers:
- Claim: comment here with the item you're taking. We add your handle next to it. One open item per person at a time.
- Fix upstream: fixes go to justinchuby/torch-onnx, unless the item says otherwise (item 8: pytorch/pytorch). Open an issue there with the item's repro, then a PR fixing it with the repro as its test. torch-onnx is maintained by one person, so wait for a go-ahead on your issue before opening the PR. Mention this tracker in both, and link them here: we check the item off when the PR is merged. microsoft/onnxscript is no longer available, so don't file there.
- Drop our patch: transformers exports through PyTorch's own
torch.onnx, which takes torch-onnx's fixes with a later PyTorch release. Once a PyTorch release ships your fix, open a PR in transformers that keeps our patch only for the PyTorch versions before it: its repro passes on the new one.
Play nice upstream: one item at a time, and never several issues or PRs at once. Projects ban accounts that flood them, and that would close the door for everyone here. I review every claim and PR myself, so please write them yourself.
- [x] No translation for
aten.unsqueezeon complex tensors β already fixed upstream in torch-onnx 2.15.0, found by @davidmorgadocarames - [x] SDPA returns
NaNfor a query row masked at every key β already fixed upstream in torch-onnx 2.15.0, found by @davidmorgadocarames - [x]
splitby a symbolic size breaks onnx_ir'sInlinePassβ already fixed upstream in torch-onnx 2.15.0, found by @samudraneel05 - [ ] No translation for
aten.randperm - [x]
chunkon a dynamic axis breaks onnx_ir'sInlinePassβ already fixed upstream in torch-onnx 2.15.0, found by @misbahulhaque1 - [x] No translation for
fill_diagonal_β fixed upstream in justinchuby/torch-onnx#237 - [x] No translation for
aten.sort.stableβ fixed upstream in justinchuby/torch-onnx#242, found by @davidmorgadocarames - [ ]
1.0 - int_tensorfails the type-promotion pass (regression in torch 2.13) - [ ]
torch.masked.mean/varexport aDivof float by int64 β claimed by @Alecbossard
Every repro imports this _check.py
"""Export `module` with `torch.onnx.export(dynamo=True)`, run it in ONNX Runtime and compare with eager."""
import numpy as np
import onnxruntime as ort
import torch
def check(module, args, dynamic_shapes=None, new_args=None, optimize=True, atol=1e-5):
program = torch.onnx.export(module, args, dynamo=True, dynamic_shapes=dynamic_shapes, optimize=optimize)
session = ort.InferenceSession(program.model_proto.SerializeToString(), providers=["CPUExecutionProvider"])
for inputs in (args, *([new_args] if new_args is not None else [])):
feeds = {i.name: a.numpy() for i, a in zip(session.get_inputs(), inputs)}
actual = session.run(None, feeds)
with torch.no_grad():
expected = module(*inputs)
expected = expected if isinstance(expected, (tuple, list)) else (expected,)
for a, e in zip(actual, expected):
np.testing.assert_allclose(a, e.numpy(), atol=atol, rtol=atol)
1. No translation for aten.unsqueeze on complex tensors
Hit by: DeepSeek-V2, Llama 4
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, x):
return torch.view_as_real(torch.view_as_complex(x).unsqueeze(0))
check(M(), (torch.randn(3, 4, 2),))
torch.onnx._internal.exporter._errors.DispatchError: No ONNX function found for <OpOverload(op='aten.unsqueeze', overload='default')>. Failure message: No decompositions registered for the complex-valued input
...
<class 'torch.onnx._internal.exporter._errors.DispatchError'>: No ONNX function found for <OpOverload(op='aten.unsqueeze', overload='default')>. Failure message: No decompositions registered for the complex-valued input
β¬οΈ
<class 'torch.onnx._internal.exporter._errors.ConversionError'>: Error when translating node %unsqueeze : [num_users=1] = call_function[target=torch.ops.aten.unsqueeze.default](args = (%view_as_complex, 0), kwargs = {}). See the stack trace for more information.
2. SDPA returns NaN for a query row masked at every key
Hit by: Parakeet
Torch returns finite values for such rows; any padded frame under a padding mask has one, and a later BatchNorm spreads the NaN over the batch (Parakeet).
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, q, k, v, mask):
return torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask)
mask = torch.zeros(1, 1, 4, 4)
mask[..., 3, :] = float("-inf") # a padded query row attending to nothing
q, k, v = (torch.randn(1, 2, 4, 8) for _ in range(3))
check(M(), (q, k, v, mask))
AssertionError:
Not equal to tolerance rtol=1e-05, atol=1e-05
nan location mismatch:
ACTUAL: array([[[[ 0.111375, 0.066215, 0.265861, 0.313686, 0.125563,
0.868579, 0.378063, -0.355591],
[-0.19523 , 0.902196, -0.507975, 0.39223 , 0.701501,...
DESIRED: array([[[[ 0.111375, 0.066215, 0.265862, 0.313686, 0.125563,
0.868579, 0.378063, -0.355591],
[-0.19523 , 0.902196, -0.507975, 0.39223 , 0.701501,...
3. split by a symbolic size breaks onnx_ir's InlinePass
Hit by: LW-DETR, RF-DETR, SegGPT
Fix goes to: justinchuby/torch-onnx: the crash is in onnxscript's constant folding (SplitToSequence), the pass after InlinePass, which the exporter runs
It lowers to SplitToSequence with a symbolic split input.
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, x):
return x.split(x.shape[0] // 2)
auto = torch.export.Dim.AUTO
check(M(), (torch.randn(8, 4),), dynamic_shapes=({0: auto},))
AttributeError: 'NoneType' object has no attribute 'ndim'
...
onnx_ir.passes.PassError: An error occurred when running the '<onnx_ir.passes.PassManager object at 0x7feb77e48850>' pass after the following passes: ['<onnx_ir.passes.common.inliner.InlinePass object at 0x7feb78007250>']
4. No translation for aten.randperm
Hit by: PatchTST, PatchTSMixer
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, x):
# The values are random: only the export and the sorted result are compared
return x[torch.randperm(x.shape[0])].sort(0).values
check(M(), (torch.arange(6.0)[:, None],))
torch.onnx._internal.exporter._errors.DispatchError: No ONNX function found for <OpOverload(op='aten.randperm', overload='default')>. Failure message: No decompositions registered for the real-valued input
...
<class 'torch.onnx._internal.exporter._errors.DispatchError'>: No ONNX function found for <OpOverload(op='aten.randperm', overload='default')>. Failure message: No decompositions registered for the real-valued input
β¬οΈ
<class 'torch.onnx._internal.exporter._errors.ConversionError'>: Error when translating node %randperm : [num_users=1] = call_function[target=torch.ops.aten.randperm.default](args = (6,), kwargs = {device: cpu, pin_memory: False}). See the stack trace for more information.
5. chunk on a dynamic axis breaks onnx_ir's InlinePass
Hit by: DiffLlama
Fix goes to: justinchuby/torch-onnx: the crash is in onnxscript's constant folding (SplitToSequence), the pass after InlinePass, which the exporter runs
DiffLlama's differential attention splits its head axis.
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, x):
a, b = x.chunk(2, dim=1)
return a - b
auto = torch.export.Dim.AUTO
check(M(), (torch.randn(2, 8, 4),), dynamic_shapes=({1: auto},), new_args=(torch.randn(2, 12, 4),))
AttributeError: 'NoneType' object has no attribute 'ndim'
...
onnx_ir.passes.PassError: An error occurred when running the '<onnx_ir.passes.PassManager object at 0x7f4b97a43490>' pass after the following passes: ['<onnx_ir.passes.common.inliner.InlinePass object at 0x7f4b97832610>']
6. No translation for fill_diagonal_
Hit by: PP-DocLayout-V4
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, x):
return x.clone().fill_diagonal_(0.0)
check(M(), (torch.randn(4, 4),))
torch.onnx._internal.exporter._errors.DispatchError: No ONNX function found for <OpOverload(op='prims.as_strided_scatter', overload='default')>. Failure message: No decompositions registered for the real-valued input
...
<class 'torch.onnx._internal.exporter._errors.DispatchError'>: No ONNX function found for <OpOverload(op='prims.as_strided_scatter', overload='default')>. Failure message: No decompositions registered for the real-valued input
β¬οΈ
<class 'torch.onnx._internal.exporter._errors.ConversionError'>: Error when translating node %as_strided_scatter : [num_users=1] = call_function[target=torch.ops.prims.as_strided_scatter.default](args = (%clone, %fill, [4], [5], 0), kwargs = {}). See the stack trace for more information.
7. No translation for aten.sort.stable
Hit by: Nemotron-H Omni
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, x):
return torch.sort(x, stable=True).values
check(M(), (torch.randn(2, 6),))
torch.onnx._internal.exporter._errors.DispatchError: No ONNX function found for <OpOverload(op='aten.sort', overload='stable')>. Failure message: No decompositions registered for the real-valued input
...
<class 'torch.onnx._internal.exporter._errors.DispatchError'>: No ONNX function found for <OpOverload(op='aten.sort', overload='stable')>. Failure message: No decompositions registered for the real-valued input
β¬οΈ
<class 'torch.onnx._internal.exporter._errors.ConversionError'>: Error when translating node %sort : [num_users=1] = call_function[target=torch.ops.aten.sort.stable](args = (%x,), kwargs = {stable: True}). See the stack trace for more information.
8. 1.0 - int_tensor fails the type-promotion pass (regression in torch 2.13)
Hit by: every model building 1.0 - attention_mask
Fix goes to: pytorch/pytorch, already tracked in pytorch/pytorch#194381: comment there instead of opening a new issue.
Tracked in pytorch/pytorch#194381, listed here for completeness.
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
def forward(self, mask):
return (1.0 - mask) * 2.0
check(M(), (torch.tensor([[1, 0, 1]], dtype=torch.int64),))
RuntimeError: Cannot find a compatible OpOverload for aten.sub with the provided arguments. Tried overloads:
Overload name Tensor:
aten::sub() Expected a value of type 'Tensor' for argument 'self' but instead found type 'float'.
Position: 0
Value: 1.0
Declaration: aten::sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
Cast error details: Unable to cast 1.0 to Tensor
Overload name Scalar:
aten::sub() Expected a value of type 'Tensor' for argument 'self' but instead found type 'float'.
Position: 0
Value: 1.0
Declaration: aten::sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
Cast error details: Unable to cast 1.0 to Tensor
Overload name out:
aten::sub() Expected a value of type 'Tensor' for argument 'self' but instead found type 'float'.
Position: 0
Value: 1.0
Declaration: aten::sub.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
Cast error details: Unable to cast 1.0 to Tensor
Overload name Scalar_out:
aten::sub() Expected a value of type 'Tensor' for argument 'self' but instead found type 'float'.
Position: 0
Value: 1.0
Declaration: aten::sub.Scalar_out(Tensor self, Scalar other, Scalar alpha=1, *, Tensor(a!) out) -> Tensor(a!)
Cast error details: Unable to cast 1.0 to Tensor
Overload name int:
aten::sub() Expected a value of type 'int' for argument 'a' but instead found type 'float'.
Position: 0
Value: 1.0
Declaration: aten::sub.int(int a, int b) -> int
Cast error details: Unable to cast Python instance of type <class 'float'> to C++ type '?' (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)
Overload name complex:
aten::sub() Expected a value of type 'complex' for argument 'b' but instead found type 'FakeTensor'.
Position: 1
Value: FakeTensor(..., size=(1, 3))
Declaration: aten::sub.complex(complex a, complex b) -> complex
Cast error details: Unable to cast Python instance of type <class 'torch._subclasses.fake_tensor.FakeTensor'> to C++ type '?' (#define PYBIND11_DETAILE
9. torch.masked.mean / var export a Div of float by int64
Hit by: PE-Audio, PE-Audio-Video
A group norm over the valid frames only.
Repro and error
import torch
from _check import check
class M(torch.nn.Module):
"""PE-Audio's group norm over the valid frames: masked mean and variance over two dims."""
def forward(self, x, padding_mask):
grouped = x.view(x.shape[0], -1, 2, x.shape[-1])
mask = padding_mask.reshape(grouped.shape).bool()
mean = torch.masked.mean(grouped, mask=mask, dim=(2, 3), keepdim=True)
var = torch.masked.var(grouped, mask=mask, dim=(2, 3), keepdim=True, unbiased=False)
return (grouped - mean) / torch.sqrt(var + 1e-5)
padding_mask = torch.ones(2, 4, 6)
padding_mask[1, :, 4:] = 0
auto = torch.export.Dim.AUTO
check(M(), (torch.randn(2, 4, 6), padding_mask), dynamic_shapes=({0: auto, 2: auto}, {0: auto, 2: auto}), atol=1e-4)
onnxruntime.capi.onnxruntime_pybind11_state.Fail: [ONNXRuntimeError] : 1 : FAIL : Type Error: Type parameter (T) of Optype (Div) bound to different types (tensor(float) and tensor(int64) in node (node_divide).
Hi @IlyasMoutawwakil, I'd like to take item 1: No translation for aten.unsqueeze on complex tensors. I'll open an issue in microsoft/onnxscript with the repro, then a PR with the fix and a test, and I'll link both here. Thank you!
Hi @IlyasMoutawwakil, I'd love to work on item 7 (aten.sort.stable). I'm going to investigate the existing code, then open an issue in microsoft/onnxscript with the repro, followed by a PR, and I'll link both here.
@saeekailas freed item 1: one item at a time across the trackers, and you're on openvino item 1. come back once that one's merged π
@MarouaZoubir all yours, added you next to item 7 π
@IlyasMoutawwakil Quick question: https://github.com/microsoft/onnxscript gives me a 404, and I couldn't find the repo under onnx/ either. Has it moved? Where should the upstream issue and PR for item 7 go?
Microsoft has been hiding its github repos lately for some reason (might be an attack or a hack), onnxruntime also disappeared, lmk if you wanna take another backend's issue, since onnx/onnxscript/onnxruntime are not available
Thnks for the heads-up Yess, I'll switch: please free item 7. I'll take OpenVINO item 18 (torch.bincount) instead and claim it on #51306.
@MarouaZoubir freed item 7 π
Note: ONNX IR is still accessible. Please feel free to contribute there, thanks!
Hi @IlyasMoutawwakil I'd love to work on Item 4
thanks for the heads up! ticked item 6 since justinchuby/torch-onnx#237 landed it π and noted that items 3 and 5 go to onnx/ir-py
@nishumbh same as on the openvino tracker: item 24 first, then come grab this one if it's still free π
Hi @IlyasMoutawwakil - here from your LinkedIn post! would love to take this slow and do things the old fashioned way with proper understanding and very selective, judicious use of ai agents. I'd like to take up item 3, if that's alright?
@samudraneel05 welcome, and love that approach, that's exactly the spirit π item 3 is yours, added you next to it. note its fix goes to onnx/ir-py (the tracker instructions just got updated for that)
Hi! Iβm interested in item 5. An AI-assisted CPU test reproduced the crash in ONNX Script 0.7.2. The traceback points to split_to_sequence in ONNX Scriptβs constant-folding pass, after InlinePass completes. Since the tracker points to onnx/ir-py and the ONNX Script repository is unavailable, where should this bug be reported?
@misbahulhaque1 great catch, you're right: the crash is in onnxscript's constant folding of SplitToSequence, the pass that runs after InlinePass, not in onnx_ir itself. since the onnxscript repo is gone, report it on justinchuby/torch-onnx: that's the exporter running that optimizer, and it tracks optimizer bugs there. item 5 is yours, added you next to it, and I fixed the tracker's pointer π
@samudraneel05 same for item 3: it crashes in that same constant folding pass, so it goes to justinchuby/torch-onnx too, sorry for the wrong pointer earlier
Hi @IlyasMoutawwakil , I looked into item 9. The repro still hits the mixed-type Div error with PyTorch 2.15.0βs built-in exporter. With torch-onnx 2.15.2, it runs on CPU and matches PyTorch for both shapes I checked: (2, 4, 6) and (3, 4, 7).
Would it be useful to open a small regression test PR in torch-onnx for this?
Hi @IlyasMoutawwakil, It seems like item 7 is free but it's already fixed in torch-onnx 2.15.2 (justinchuby/torch-onnx#242), the repro passes, and results match Pytorch even when repeated values that is when it matters. Btw the patch in transfomers hasn't been removed yet, i would like to open a PR to remove it if possible. Thanks!
Hi Ilyas, quick update on item 5. In an AI-assisted check, PyTorch 2.15.0βs built-in exporter reproduced the SplitToSequence constant-folding crash with optimization enabled. Standalone torch-onnx 2.15.2 exported the same example successfully, and ONNX Runtime matched PyTorchβs output for both input shapes: (2, 8, 4) and (2, 12, 4). Since the standalone exporter passes this example, would you still like me to open a separate upstream issue?
@misbahulhaque1 thanks for checking! since torch-onnx 2.15.2 already passes it, no need for a new upstream issue: it's fixed there, likely by justinchuby/torch-onnx#220. could you check which torch-onnx release first passes it (2.15.0, 2.15.1 or 2.15.2)? then I'll check item 5 off with the right link π
@Alecbossard same story for item 9: it's already fixed in torch-onnx 2.15.2, likely by justinchuby/torch-onnx#243. could you confirm the same way (the first release that passes it)? item 9 is yours to wrap up, added you next to it. a regression test in torch-onnx is a good idea, but open an issue there first and wait for a go-ahead, as the tracker asks: torch-onnx is maintained by one person
@davidmorgadocarames nice find, thanks! checked item 7 off with justinchuby/torch-onnx#242. for the patch, not yet though: transformers exports through PyTorch's own torch.onnx, which only gets torch-onnx's fixes with a later PyTorch release, so dropping it now would break everyone on torch 2.15. once a PyTorch release ships #242, a PR keeping our patch only for the older versions is yours. I updated step 3 to say so π