Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mlx - implement fft2, rfft, and irfft and fix fft #20781

Merged
merged 1 commit into from
Jan 18, 2025
Merged
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
48 changes: 40 additions & 8 deletions keras/src/backend/mlx/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,24 +54,56 @@ def extract_sequences(x, sequence_length, sequence_stride):
return x.reshape(*batch_shape, frames, sequence_length)


def _get_complex_tensor_from_tuple(x):
if not isinstance(x, (tuple, list)) or len(x) != 2:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and imaginary."
f"Received: x={x}"
)
real, imag = x
real = convert_to_tensor(real)
imag = convert_to_tensor(imag)
# Check shapes.
if real.shape != imag.shape:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and imaginary."
"Both the real and imaginary parts should have the same shape. "
f"Received: x[0].shape = {real.shape}, x[1].shape = {imag.shape}"
)
# Ensure dtype is float.
if not mx.issubdtype(real.dtype, mx.floating) or not mx.issubdtype(
imag.dtype, mx.floating
):
raise ValueError(
"At least one tensor in input `x` is not of type float."
f"Received: x={x}."
)
complex_input = mx.add(real, 1j * imag)
return complex_input


def fft(x):
x = convert_to_tensor(x)
return mx.fft(x)
x = _get_complex_tensor_from_tuple(x)
complex_output = mx.fft.fft(x)
return mx.real(complex_output), mx.imag(complex_output)


def fft2(x):
# TODO: https://ml-explore.github.io/mlx/build/html/python/fft.html#fft
raise NotImplementedError("fft not yet implemented in mlx")
x = _get_complex_tensor_from_tuple(x)
complex_output = mx.fft.fft2(x)
return mx.real(complex_output), mx.imag(complex_output)


def rfft(x, fft_length=None):
# TODO: https://ml-explore.github.io/mlx/build/html/python/fft.html#fft
raise NotImplementedError("fft not yet implemented in mlx")
x = convert_to_tensor(x)
complex_output = mx.fft.rfft(x, n=fft_length)
return mx.real(complex_output), mx.imag(complex_output)


def irfft(x, fft_length=None):
# TODO: https://ml-explore.github.io/mlx/build/html/python/fft.html#fft
raise NotImplementedError("fft not yet implemented in mlx")
x = _get_complex_tensor_from_tuple(x)
real_output = mx.fft.irfft(x, n=fft_length)
return real_output


def stft(
Expand Down
Loading