fix(fft): handle len==1 input without panicking#272
Open
sashaphmn wants to merge 1 commit into
Open
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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