Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions mlx/backend/metal/fft.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,10 @@ void fft_op(
out_data_size,
out_strides,
in_contiguous.flags());
} else {
// Reuse the buffer with this step's layout.
out.copy_shared_buffer(
out, out_strides, in_contiguous.flags(), out_data_size);
}

auto radices = supported_radices();
Expand Down Expand Up @@ -830,6 +834,15 @@ void fft_op(
fft_op(in, out, axis, inverse, real, FourStepParams(), inplace, s);
}

// The n == 1 and multi upload Bluestein paths replace the buffer of out.
bool fft_supports_inplace(int n) {
if (n == 1) {
return false;
}
auto plan = plan_fft(n);
return !plan.four_step || plan.bluestein_n == -1;
}

void nd_fft_op(
const array& in,
array& out,
Expand Down Expand Up @@ -863,8 +876,8 @@ void nd_fft_op(
}
for (int i = filtered_axes.size() - 1; i >= 0; i--) {
int reverse_index = filtered_axes.size() - i - 1;
// For 5D and above, we don't want to reallocate our two temporary arrays
bool inplace = reverse_index >= 3 && i != 0;
// Reuse the two temporaries once both exist.
bool inplace = reverse_index >= 2 && i != 0;
// Opposite order for fft vs ifft
int index = inverse ? reverse_index : i;
size_t axis = filtered_axes[index];
Expand All @@ -873,6 +886,12 @@ void nd_fft_op(
bool step_real = (real && index == filtered_axes.size() - 1);
const array& in_arr = i == filtered_axes.size() - 1 ? in : temp_arrs[i % 2];
array& out_arr = i == 0 ? out : temp_arrs[1 - i % 2];
if (inplace && !fft_supports_inplace(in_arr.shape(axis))) {
// Earlier kernels still read the old buffer.
metal::get_command_encoder(s).add_temporary(out_arr);
out_arr = array(temp_shape, complex64, nullptr, {});
inplace = false;
}
fft_op(in_arr, out_arr, axis, inverse, step_real, inplace, s);
}

Expand Down
21 changes: 21 additions & 0 deletions python/tests/test_fft.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,27 @@ def test_fftn_size_one_axes(self):
s=sizes,
)

def test_fftn_many_axes(self):
# Each step of a 4+ axis transform needs its own temporary.
for shape in [(8, 6, 10, 12), (4, 6, 8, 5, 6), (3, 4, 5, 4, 3, 4)]:
r = np.random.randn(*shape).astype(np.float32)
c = r + 1j * np.random.randn(*shape).astype(np.float32)
for op in ["fftn", "ifftn", "rfftn", "irfftn"]:
with self.subTest(shape=shape, op=op):
x = r if op == "rfftn" else c
kwargs = {"axes": tuple(range(len(shape)))}
if op == "irfftn":
x = np.fft.rfftn(r)
kwargs["s"] = shape
self.check_mx_np(
getattr(mx.fft, op),
getattr(np.fft, op),
x,
atol=1e-4,
rtol=1e-5,
**kwargs,
)

def test_fft_into_ifft(self):
n_fft = 8193
mx.random.seed(0)
Expand Down
Loading