onnx icon indicating copy to clipboard operation
onnx copied to clipboard

Clarify DFT behavior when `inverse=True`

Open justinchuby opened this issue 1 year ago • 3 comments
trafficstars

Currently, https://onnx.ai/onnx/operators/onnx__DFT.html specifies the input/output relations for DFT, but it does not specify what those when inverse=True. This can create confusion on, for example, whether both onesided and inverse can be set, and what the input/output shapes should be.

cc @xadupre @gramalingam

justinchuby avatar Feb 08 '24 17:02 justinchuby

Good point. But is onesided mathematically meaningful for inverse (when the input is real)? The resolution probably depend on that.

gramalingam avatar Feb 12 '24 17:02 gramalingam

Maybe expect that given an input x, DFT(DFT(x, onesided=True), reversed=True, onesided=True)) == x?

I think similar to https://numpy.org/doc/stable/reference/generated/numpy.fft.irfft.html

justinchuby avatar Feb 12 '24 23:02 justinchuby

@justinchuby hi, how to correctly export torch.fft.irfft into onnx? Here is my code:

import torch
from torch import nn
import onnxruntime as ort
import numpy as np

class Model(nn.Module):
    def forward(self, x):
        fft = torch.fft.rfft(x)
        ifft = torch.fft.irfft(fft)
        return fft, ifft
    
input = torch.randn(1, 1024)
model = Model()

torch.onnx.dynamo_export(
    model,
    (input)
).save("/home/xinghq/dy.onnx")

ort_session = ort.InferenceSession("/home/xinghq/dy.onnx")
input_names = [input.name for input in ort_session.get_inputs()]
output_names = [output.name for output in ort_session.get_outputs()]

input_data = np.random.randn(1, 1024).astype(np.float32)

input_dict = {
    input_names[0]: input_data
}

outputs = ort_session.run(output_names, input_dict)
print (outputs[0].shape) 
print (outputs[1].shape)

(1, 513, 2)
(1, 513)

With input shape (1, 1024), rfft results (1, 513, 2) is correct, but irfft should return (1, 1024) instead of (1, 513). I checked the onnx operator attributes of second DFT with onesided=0, which is expected to be 1. I mannually changed it to 1 and inference, then I got error message: is_onesided and inverse attributes cannot be enabled at the same time.

XhqGlorry11 avatar Jul 31 '24 02:07 XhqGlorry11