FFTs Part 6: The FFT-20XX Real-Input Algorithm(s)
Here it is, the final part of this series of posts about FFTs and the specific algorithms that FFT-20XX uses.
- The Discrete Fourier Transform
- The Basics of the FFT
- Some Optimizations to the FFT
- The Inverse FFT
- The FFT-20XX Complex-Input Algorithm
- The FFT-20XX Real-Input Algorithm(s) (← you are here)
Over five posts we’ve gone over way more about the FFT than I ever intended to write, up to and including the complex-input algorithm used by FFT-20XX.
But one thing we haven’t gone over yet is how to deal with purely real-valued inputs (like, for instance, most audio and video applications).
This took me a hot minute to get right and was effectively the final boss of the whole project! Once again, we can’t just jump right in — first, we need to talk about real-input FFTs.
Real-Input FFTs
For FFTs where the inputs are only real values (like audio samples), at first glance it may seem like there isn’t enough memory to store all of the results. For example, a 256-element real-input FFT would have 256 real (scalar) inputs, but generate 256 complex outputs (each of which contains two scalars), which means it seems like we’d need 512 scalars worth of output data.
But, if we go all the way back to part 1 of this series and play around with the diagrams again, we’ll note that the DFT creates the folowing values:
- The first element is the DC bias (or DC offset). This is always a real value when there are only real inputs (as all of the rotations are 0, so nothing ever ends up in the complex (y) component).
- The next values are complex, representing the (non-zero) frequencies below the Nyquist frequency.
- The value at index represents the aforementioned Nyquist frequency, and — like the DC bias — is always a real value when the inputs are real (as the rotations are either 0 or 180 degrees, which is effectively only ever a scale of 1 or -1).
- The remaining values are complex, but they are (in reverse order) the complex conjugates of the other complex values when the inputs are all real values (they are still distinct values for complex inputs)
So what we have are complex values, 2 real values, then the rest are effetively redundant, as they’re the same as the other complex values but with the opposite sign on the imaginary component.NoteThe complex conjugates are in the opposite order from each other. If you recall that our angles look like:
0, 1, 2, 3, 4, -3, -2, -1Angles 1 and -1 are conjugates, 2 and -2 are conjugates, etc.
This little reversal caused me a lot of headache while trying to get this all to work, as you’ll see in a bit!
Conveniently, that’s scalar values, which fits exactly in the same amount of space as our inputs!
NoteTraditionally, to keep the complex pairs together, the Nyquist value gets moved to be paired with the DC value, so the memory layout ends up like:
, , , , , , …, ,
That’s great! Now we know that we can store the values in the same amount of memory, now we just need to figure out how to compute the values in half the usual memory!
Computing the Real-Input FFT
There are a few techniques that people have used to calculate the FFT of purely real-valued data. One trick (illustrated here) is to compute two halves of the real FFT at the same time using a single (-length) complex FFT, then combine the two halves into the final result with a single radix 2 step. This works well, but there are more-efficient ways to do it.
Instead, we’ll start with an idea from this 1968(!) paper by Glenn D. Bergland.
Remember that the (radix-2) decimation in time algorithm does a pass of standard 2-element FFTs, then a pass of 4-element FFTs, etc:
We can take advantage of the fact that every real-valued FFT has two real output values (DC and Nyquist) and the rest are complex conjugate pairs.
Here’s that diagram again, this time with known-real values labeled with blue squares, the “necessary” complex values labeled with green up-pointing triangles, and the redundant conjugate complex values labeled with red down-pointing triangles (some of the triangles have circles on them, I’ll explain those in a moment):
There are some interesting things to note here:
- The first pass has only real outputs: Because there are no rotations involved, it’s just an add/sub step, leaving everything still real.
- In the next step, half of its outputs are real. This makes sense: two outputs get computed with no rotation and two with a 90-degree rotation (which end up as conjugates of each other).
- From the second step on, every step has half the number of real outputs as the step before, ending when there are just two
left (DC and Nyquist). Each sub-FFT (past the first) has four real inputs, and of those, one pair is used without rotation, leaving
them real.
- The other pair of real inputs to these sub-FFTs, it’s worth noting (because we’ll use this later), is always done with a 90-degree rotation. This is what the small circles on those values signify.
If we instead visualize this with standard-order inputs and bit-reversed outputs, it can give us even more insight:
Viewed this way:
- The halving of the number of real values after the first step is much easier to see, as we keep them all contiguous.
- In this ordering, DC and Nyquist end up next to each other at the end, exactly as we want for our final output!
- Every complex value in the final output is paired with a conjugate value.
- Note that these are not necessarily paired conjugates (see the note earlier about how the pairs of conjugate values are in the opposite order from each other).
- Every computation step (the circular nodes) with complex inputs kicks out one “standard” complex value and one
“redundant” value.
- Again, these are not always conjugates of each other!
- The 90-degree rotations (the arrows with circles on them) are always the first set of complex conjugate pairs after the real outputs (as they are the output from the half of the real inputs to this step that were rotated).
Zeroing in on that third point, if every computation kicks out one redundant complex value, we can use that to our advantage: instead of storing that redundant value, we could use its storage to hold the imaginary value for the non-redundant output. That gives us enough space to do the whole computation in the memory we were provided!
To figure out the best way to do that, let’s go back to one of our diagrams from part 2, showing the way that the elements interleave during the FFT computation:
Now we’re going to relabel the redundant conjugates’ indices to correlate them with their matches (recoloring to match the above butterfly diagram, and using “R” and “i” to show which gets the real and imaginary components):
Now, let’s rearrange the rows of this to have the inputs in standard order (to match the butterfly diagrams above):
Now we can see that we hypothetically have space for everything, but if we keep things in their standard order, we end up with complex pairs that are not actually correlated (note how is followed by , etc).
Ignoring that for a moment, let’s look at what we have to do to even make this work (sticking to radix-2 for now).
For any given radix-2 computation involving complex inputs, we actually end up needing to load two at once, because both the “real” and “imaginary” component still represent two distinct values (the complex conjugates and ), and thus are used to get two different sets of outputs.
To illustrate this, we’ll use a modified butterfly diagram, showing the two pairs (one real, one imaginary) that go into each value, and the corresponding values that come out:
NoteI left the rotations off of this diagram, mostly because I couldn’t figure out where to put them.
Welp. This is a bit more of a mess than our previous diagrams due to the overlapping ranges here. Each computation that has complex inputs, as we said, has two pairs of inputs, and writes to two pairs of outputs.
Importantly: The indices for input and output per computation are always the same, though which values get paired changes from input to output.
In addition to the real and imaginary components not ending up paired (again, note that is paired with , which is not its imaginary part), the other problem with this arrangement is that it very much does not SIMD well. Plus, even if it did, it ends up causing problems when we get to doing the incremental bit reversal (similar to how the complex-input did it)!
NoteSpecifically, once this gets squished together into radix-4 and there are passes loading 4 sets of radix-4s to do the bit flips, as it gets closer to the end for larger FFT sizes (ones that would be prohibitive to diagram here), there end up being long dependency chains through the various butterflies needed, and frequently the final step requires all of them be computed at once in order to properly do the final bit flip pass!
That’s not ideal.
But, going back to that paper by Glenn D. Bergland, we can change the order in which we save out the imaginary components, such that things end up staying paired:
At first glance, this looks great! A given set of “real” values (the non-redundant complex values) is now followed by its corresponding “imaginary” parts (its complex conjugate) at every step, which is what we were looking for! If we do a butterfly diagram again, it’s a lot more regular-looking than the last one:
So it seems like maybe this is the point where we start in on the bit-reversal like we did with the complex-input FFT. Buuuuut before we do that, we can make this a little more efficient!
90 Degree Rotations
This whole time we’ve been labeling the complex values that are the result of a 90-degree rotation with the promise that it was going to be important. Well, the time is nigh!
As we’ve gone over many times, the decimation in time algorithm rotates the second input and then adds it to and subtracts it
from the first input to get the two outputs for a given computation step:
In the event that we’re rotating by (negative) 90 degrees, is just :
If and are both real numbers (which they are, for our 90-degree rotations), and we’re only writing out the first complex output (where the real component goes where lives and the imaginary component goes where we would put ), then the value at the location of / is completely unchanged (the real component of is ), and the value at the location of / is just negated (the imaginary component of is ).
An ExampleIf we have the two input values and for a radix 2 butterfly with a quarter-turn rotation, rotating the latter (as it’s our odd input) turns it into . Thus the sum for ends up being .
Because we’re only writing out (putting its imaginary component where would go in a complex FFT), one value written is and one is .
And since these are being written to the same 2 indices that the inputs came from, the end result (in memory) is simply a negation of the second input: the remains unchanged, and the is negated.
So let’s redraw the diagram again, making those parts be pass-through, except for a negation (represented by a long red rectangle):
So now there are these blocks where nothing is happening except a negation!
If we, instead, moved the negation to the end of the previous phase (when writing those values out), we can collapse all of those down (shifting everything after one of these negation-only passes to the left in the diagram), removing almost one entire pass (everything except the computation of outputs 0 and 8):
This gives us two nice properties:
- The main one: now instead of steps, we are doing steps (with a single addition and subtraction at the end to compute the final two values).
- The real groups are all consistent, and the last half of each real group negates the second outputs (outputting instead of ).
Now we’re doing less work, and it’s all very regular in how it works (which means good things for SIMD implementation!), so finally it’s time to handle…
Bit Reversal
Two related things change the way we do the bit reversal in this:
- We’ve managed to work our equation such that we have all of the pairs of values (DC/Nyquist and the real/imaginary pairs) together already, so we don’t want to break those up.
- There are half as many complex outputs as with a complex FFT (counting DC and Nyquist as one), since we’re dropping the redundant complex conjugates.
Turns out, instead of doing the bit reversal for all elements, we actually reverse in pairs instead! So, in our 16-element example, we do the reversal as if it were 8 elements, which means there is only one bit reversal instead of two (since 8 elements has 3-bit indices, so the outer two bits swap and the middle one stays put).
The method we use to do the bit reversal is effectively the same as with the complex FFT: the last half of the radix-2 steps each do a middle-out bit reverse.
NoteAnd, accordingly, when we get to radix-4, each radix-4 pass reverses a pair of bits, which turns into a 4×4 transpose, exactly the same as with the complex implementatione (except, of course, when one pass needs to only do a single reverse due to an odd number of bit reversals).
Conveniently, all of the same patterns we found in the complex-input version still apply!
So let’s finish up our diagram by doing the single bit reversal at the end (admittedly not as useful as if there were more bit reversals, but like hell am I making any larger diagrams):
And there we are! Now all of the outputs are in the order we … uh …
Wait, why are 7 and 5 not in the right spot?
NoteThis was a real “Well, shit” moment while I was working on this. This ordering is even in the 1968 paper and I didn’t notice it, because I was so used to seeing the bit-reversed orderings at that point I just assumed.
Reversals Within Reversals
It turns out, back when we rearranged everything to be more regular and get our final pairs together, this also changed the ordering of the components! (If you go back and look at the diagrams before and after we did this, you can see and swap places).
NoteAlso, importantly: the angles used for the rotations through the algorithm are also reversed using this same pattern (but in bit-reversed order), so that needs to be taken into account!
The reversal is just barely noticeable at 16 elements, but as we add more, it gets worse and worse. Here’s a grid showing the index pairs of a 128-element FFT (where “0” would contain DC and nyquist) and how they’re flipped (relative to standard order):
What. Even.
It turns out that, due to the way we flipped around the imaginary values that we write at each level, there is a corresponding flip of the outputs. Here’s the indices for 32 elements in a big column showing the reversals:
The process to undo this, then, is as follows:
- Every 8 pairs of elements, reverse the order of the last 3
- Every 16 pairs of elements, reverse the order of the last 7
- Every 32 pairs of elements, reverse the order of the last 15
- …
- Every N pairs of elements, reverse the order of the last
NoteThe pattern here is closely related to Gray code, which is a special ordering of values where only one bit changes as the value increments or decrements (major credit to Matthijs De Smedt who figured out the pattern).
The actual code to go from a standard-order index to the “tangled” index above is:
size_t TangleIndex(size_t i) { auto mask = (i & (i - 1)) >> 1; mask ^= mask >> 32; mask ^= mask >> 16; mask ^= mask >> 8; mask ^= mask >> 4; mask ^= mask >> 2; mask ^= mask >> 1; return (i - (mask & 1)) ^ mask; }I honestly don’t remember how I derived that anymore, but that middle bit with the xors and shifts is exactly the routine to convert a 32-bit Gray code value back to its standard binary representation.
Here’s the one thing that bummed me out coming up with this algorithm: I was unable to find a nice iterative way to handle this (every attempt led to some breakdown of regularity or to giant dependency chains), so this ended up as a post-process step at the end.
But, it’s still way less costly than a full bit-reverse pass, as there are nice ways to do this operation in larger chunks, which can be done fairly efficiently in SIMD on both x64 and ARM.
The Algorithm!
Ultimately, the implementation in FFT-20XX was done in radix-4 instead of the radix-2 we’ve been discussing thus far. I’m not going to go through getting it into radix-4 because, honestly, it’s not the important part, and is just a set of uninteresting, mechanical steps.
Like the complex FFT, it does the bit reversal iteratively, 2 bits at a time at the last half of the transform, except we do the above trickery to compute only the half of the outputs that we need in the space that we have.
Finally, after all that, it does an “untangle” pass to get from, uh, whatever order that is into standard order.
There is a reference implementation checked in here.
The main routine is titled RealForwardReference.
The Inverse
The one downside of real FFTs is that, unlike with the complex FFT, we cannot use the same base routine to invert this process. Instead, like in part 4, we need to straight-up do the whole process in reverse (ending up with a DIF-like routine):
- We start by “re-tangling” the inputs such that they’re in the weird order from the end of our forward routine
- Then do a series of DIF steps that are the inverse of the steps we did to get here, with every step (except the last one) having twice as many real values as the one before, doing the bit-reverse steps in the first half this time (since those were the last-half steps of the forward algorithm).
Like the forward algorithm there is a reference implementation
for this, called RealInverseReference.
SIMD Considerations Again
The optimization of this routine was relatively straightforward: using SIMD operations and doing the bit reversals works very similarly to the complex routine, all of the same tricks apply.
As with the complex routine, as the FFTs get smaller, there are some special-cases that needed to be done. For AVX’s 8-element vectors, FFTs smaller than 128 are done via SSE2, and FFTs smaller than 32 are done purely in scalar.
The untangle was also done by doing the process in blocks, and working as locally as possible to try to stay within CPU cache as much as it can.
Additionally, the table ends up being stored differently: The table entries are stored in “tangled” order rather than the standard order (which means the cos/sin values can’t be overlapped like with the complex version). However, it turns out that we need half as many angles in the table (due to the lack of computing the redundant values), so the table ends up being a bit smaller than the complex-input one (it is the size).
Finally
And we’re finally through this gauntlet of bit reversals, other reversals, and diagrams!
If you read this far: wow, I honestly didn’t expect anyone to! Hopefully you found this interesting (or at least understandable).
And now I’m going to try to stop thinking about FFTs for a while.