Skip to content

fix(fft): handle len==1 input without panicking#272

Open
sashaphmn wants to merge 1 commit into
Lagrange-Labs:masterfrom
sashaphmn:fix/fft-len-one-panic
Open

fix(fft): handle len==1 input without panicking#272
sashaphmn wants to merge 1 commit into
Lagrange-Labs:masterfrom
sashaphmn:fix/fft-len-one-panic

Conversation

@sashaphmn

Copy link
Copy Markdown

Handle len == 1 in fft() with an early return to avoid a panic caused by the radix-2 implementation assuming n >= 2. Add regression tests for both FFT and inverse FFT

fft() states its precondition only via
ensure!(v.len().is_power_of_two()), and 1usize.is_power_of_two() ==
true. The implementation, however, unconditionally writes to
twiddle[1], even though twiddle has length 1 when v.len() == 1,
causing an out-of-bounds panic. Before reaching that point,
bitreverse_permutation also computes a right-shift of
usize::BITS - length.ilog2() bits, which equals a full-width shift
for length == 1 and panics under overflow-checks. Both failures
share the same root cause: the n == 1 case was never handled by the
general radix-2 code path, which assumes n >= 2.

A length-1 FFT is mathematically the identity transform, so handling
this case with an early return preserves correctness while avoiding
the panic.

Reachability: all current call sites of fft() in
zkml/src/layers/convolution/mod.rs construct their input length as
2 * n_x * n_x or 2 * filter_size(shape), which is structurally >= 2.
So this was a latent API defect, not reachable through any existing
call path, but it violates the function's documented precondition
and would panic for any future or external caller passing a
single-element vector.

Adds minimal PoC regression tests (fft_single_element_should_not_panic,
ifft_single_element_should_not_panic) that reproduce the panic before
this fix and pass after it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant