Export PyTorch model to ONNX / OpenCV

Hello everyone,

Using version PyTorch 2.9, the default behavior of torch.onnx.export changed as it now defaults to dynamo=True. According to the docs:

Setting dynamo=True enables the new ONNX export logic which is based on torch.export.ExportedProgramand a more modern set of translation logic. This is the recommended and default way to export models to ONNX.

However, this leads to a breaking change by importing the ONNX files into OpenCV. Minimum example using a dummy model:

import cv2 as cv
import torch
from torch import nn

model = nn.Sequential(
    nn.Conv2d(3, 4, (5,5)),
    nn.ReLU(),
    nn.MaxPool2d((2,2)),
    nn.Flatten(),
    nn.Linear(15376, 42))
input = torch.zeros((1, 3, 128, 128), dtype=torch.float32)
torch.onnx.export(model, input, 'model1.onnx', dynamo=False)
torch.onnx.export(model, input, external_data=False).save('model2.onnx')

cv.dnn.readNetFromONNX('model1.onnx') # ok
cv.dnn.readNetFromONNX('model2.onnx') # error

Importing the second model into OpenCV fails:

cv2.error: OpenCV(4.12.0) opencv\modules\dnn\src\onnx\onnx_importer.cpp:1058: error: (-2:Unspecified error) in function ‘cv::dnn::dnn4_v20250619::ONNXImporter::handleNode’
Node [Conv@ai.onnx]:(onnx_node!node_conv2d) parse error: OpenCV(4.12.0) opencv\modules\dnn\src\layers\layers_common.cpp:106: error: (-5:Bad argument) kernel_size (or kernel_h and kernel_w) not specified in function ‘cv::dnn::util::getKernelSize’

We tested to adjust some export parameters, however found no solution besides switching back to the TorchScriptONNX export using dynamo=False.

As long as this is still possible, the issue is no big deal. Still we are curious whether it is possible to export an OpenCV-compatible ONNX file using torch.export.ExportedProgram as TorchScript could be deprecated (sooner or later)? Or do we simply have to wait for OpenCV to support more recent ONNX files?