`torch.irfft` and `np.fft.irfft` disagree

Hello!

Suppose I have a tensor of shape [N,] with real entries. Then, np.fft.rfft(x) and torch.rfft(x) produce the same output (i.e. they are np.allclose).

However, taking the respective irffts of both of these FFTs return different outputs. Firstly, the two outputs are of different shapes. Secondly, the values are different: comparing them with np.allclose fails: in fact, not a single pair of values in their Cartesian product are close. I’ve attached a minimal reproducible example below.

I’m not sure what I’m doing wrong here: any help would be appreciated! Thanks!

import numpy as np
import torch
import itertools

x = np.random.randn(100).astype(np.float32)

# IFFT(FFT(x)) == x
fft_np = np.fft.rfft(x)
ifft_np = np.fft.irfft(fft_np)
assert np.allclose(x, ifft_np)

# Same thing but in PyTorch
x = torch.tensor(x)
fft_torch = torch.rfft(x, signal_ndim=1)
ifft_torch = torch.irfft(fft_torch, signal_ndim=1).numpy()

# The FFTs are np.allclose
fft_torch = fft_torch.numpy()
assert np.allclose(np.real(fft_np), fft_torch[:, 0])
assert np.allclose(np.imag(fft_np), fft_torch[:, 1])

# But the IFFTs have different shapes
print(ifft_np.shape)     # (100,)
print(ifft_torch.shape)  # (101,)

# And none of their values are np.allclose
print(np.allclose(ifft_np, ifft_torch[:-1]))  # False
print([x for (x, y) in itertools.product(ifft_np, ifft_torch)
       if np.allclose(x, y)])  # []

Just posted this on the GitHub issue tracker (see below). The tldr is that I didn’t read the docs carefully enough! The following code snippet will run.

from numpy import allclose
import torch

x = torch.randn(100)
rfft = torch.rfft(x, signal_ndim=1)
irfft = torch.irfft(rfft, signal_ndim=1,
                    onesided=True, signal_sizes=x.shape).numpy()

assert allclose(x, irfft, rtol=1e-4)