JoshJers' Ramblings

Infrequently-updated blog about software development, game development, and music

Posts tagged “fft”

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.

  1. The Discrete Fourier Transform
  2. The Basics of the FFT
  3. Some Optimizations to the FFT
  4. The Inverse FFT
  5. The FFT-20XX Complex-Input Algorithm
  6. 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 N2−1\frac{N}{2} - 1 values are complex, representing the (non-zero) frequencies below the Nyquist frequency.
  • The value at index N2\frac{N}{2} 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 N2−1\frac{N}{2} - 1 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)
Note

The 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, -1

Angles 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!

So what we have are N2−1\frac{N}{2} - 1 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.

Conveniently, that’s NN scalar values, which fits exactly in the same amount of space as our inputs!

Note

Traditionally, 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:
 vdcv_{dc}, vnyqv_{nyq}, r1r_1, i1i_1, r2r_2, i2i_2, …, rN/2−1r_{N/2-1}, iN/2−1i_{N/2-1}

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 (N2\frac{N}{2}-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:

A standard 16-element radix-2 diagram. " " 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

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):

A standard 16-element radix-2 diagram, where the values have been color-coded by function as described above. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

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:

The same 16-element FFT diagram, except reordered as described above. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 4 2 6 1 5 3 7 0 0 4 4 2 2 6 6 0 0 0 0 4 4 4 4 0 0 0 0 0 0 0 0

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:

A diagram (originally from part 2) showing the inputs on the left in bit-reversed format, then they interleave in groups of 4, then 8, then 16, before ending up in standard, ascending order as outputs on the right. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 4 8 12 2 6 10 14 1 5 9 13 3 7 11 15 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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):

The same diagram as above, but this time with the values color-coded as to whether they are real, complex, or the complex conjugate, and the conjugates have been re-labeled to show the index of the value they are the conjugate of. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 4R 8 4i 2 6R 10 6i 1 5R 9 5i 3 7R 11 7i 0 2R 4R 6R 8 6i 4i 2i 1 3R 5R 7R 9 7i 5i 3i 0 1R 2R 3R 4R 5R 6R 7R 8 7i 6i 5i 4i 3i 2i 1i

Now, let’s rearrange the rows of this to have the inputs in standard order (to match the butterfly diagrams above):

A diagram similar to the above, but reordered such that the inputs on the left are in standard, ascending order and the outputs on the right are in the bit-reversed order. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 8 9 10 11 4R 5R 6R 7R 4i 5i 6i 7i 0 1 8 9 4R 5R 4i 5i 2R 3R 6i 7i 6R 7R 2i 3i 0 8 4R 4i 2R 6i 6R 2i 1R 7i 5R 3i 3R 5i 7R 1i

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 1R1_R is followed by 7i7_i, 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 vR+iviv_R + i v_i and vR−iviv_R - i v_i), 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:

Note

I left the rotations off of this diagram, mostly because I couldn’t figure out where to put them.

A modified radix-2 butterfly diagram showing the pattern of accesses necessary to use the real and imaginary components (stored separately) to compute their corresponding outputs. It's a bit of a mess. 0 8 4R 4i 2R 6i 6R 2i 1R 7i 5R 3i 3R 5i 7R 1i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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 1R1_R is paired with 7i7_i, 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)!

Note

Specifically, 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:

The block interleave diagram again, but this time with the imaginary components stored in different orders, and how that filters through the system. The output pairs are now correlated (the real and imaginary components are stored contiguously). 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 8 9 10 11 4R 5R 6R 7R 4i 5i 6i 7i 0 1 8 9 4R 5R 4i 5i 2R 3R 2i 3i 6R 7R 6i 7i 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i

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:

A modified radix-2 FFT diagram showing this new ordering. It is considerably less messy than the last attempt. 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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:
 y0=x0+kx1y_0 = x_0 + k x_1
 y1=x0−kx1y_1 = x_0 - k x_1

In the event that we’re rotating by (negative) 90 degrees, kk is just −i{-}i:
 y0=x0−ix1y_0 = x_0 - i x_1
 y1=x0+ix1y_1 = x_0 + i x_1

If x0x_0 and x1x_1 are both real numbers (which they are, for our 90-degree rotations), and we’re only writing out the first complex output y0y_0 (where the real component goes where y0y_0 lives and the imaginary component goes where we would put y1y_1), then the value at the location of x0x_0/y0Ry_{0R} is completely unchanged (the real component of y0y_0 is x0x_0), and the value at the location of x1x_1/y0iy_{0i} is just negated (the imaginary component of y0y_0 is −x1{-}x_1).

An Example

If we have the two input values x0=8x_0 = 8 and x1=3x_1 = 3 for a radix 2 butterfly with a quarter-turn rotation, rotating the latter (as it’s our odd input) turns it into −3i-3i. Thus the sum for y0y_0 ends up being 8−3i8 - 3i.

Because we’re only writing out y0y_0 (putting its imaginary component where y1y_1 would go in a complex FFT), one value written is 88 and one is −3-3.

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 88 remains unchanged, and the 33 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):

A similar diagram to the last radix-2 diagram, except where there were real values being processed into complex pairs, instead we have denoted that no work happens (besides the imaginary outputs being negated). 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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):

The same diagram as above, except the "no work being done" sections have been collapsed, so overall there is one less pass of FFT calculation. The only exception are the first two outputs (indexed 0 and 8), which remain real the whole time and thus cannot collapse. 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

This gives us two nice properties:

  1. The main one: now instead of log⁡ N\log\,N steps, we are doing (log⁡ N)−1(\log\,N) - 1 steps (with a single addition and subtraction at the end to compute the final two values).
  2. The real groups are all consistent, and the last half of each real group negates the second outputs (outputting x1−x0x_1 - x_0 instead of x0−x1x_0 - x_1).

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:

  1. 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.
  2. 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 NN elements, we actually reverse in N2\frac{N}{2} 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.

Note

And, 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):

The same diagram as before, except now we've added a paired bit reverse step at the end, putting things into an order that is *almost* but not quite sequential. 0 8 1R 1i 2R 2i 3R 3i 4R 4i 7R 7i 6R 6i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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?

Note

This 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 5R5_R and 7R7_R swap places).

Note

Also, 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:

A display of 32 indices (representing pairs of elements in a 64-element real FFT), and the sections that are reversed 0 1 2 3 4 7 6 5 8 15 14 13 12 9 10 11 16 31 30 29 28 25 26 27 24 17 18 19 20 23 22 21

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 N2−1\frac{N}{2} - 1
Note

The 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 23\frac{2}{3} 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.

FFTs Part 5: The FFT-20XX Complex-Input Algorithm

This is part 5 of a series of posts about FFTs and the specific algorithms that FFT-20XX uses.

  1. The Discrete Fourier Transform
  2. The Basics of the FFT
  3. Some Optimizations to the FFT
  4. The Inverse FFT
  5. The FFT-20XX Complex-Input Algorithm (← you are here)
  6. The FFT-20XX Real-Input Algorithm(s)

Over the last four posts, we dug into how the FFT works, various ways to compute it (some more efficient than others), and how to invert the process (to go from frequency space back into the time domain).

Now it’s finally time to start in on the specifics of how FFT-20XX’s algorithms work, starting with the algorithm for fully-complex inputs (which, despite the name, is the simpler of the algorithms).

Will this make any sense to anyone but me? Who knows. Will it even make sense to me 6 months after I write this? Who knows.

If you’re still with me on this FFT journey, strap in, cuz here we go!

The Requirements

Before we start getting into how it works, I wanted to take a moment to spell out the properties I wanted FFT-20XX to have. For a variety of reasons, I wanted the following to be true:

  1. No scratch memory should be required. There are many (quite fast!) implementations out there that require writable memory in which to store temporary results. If doing multiple FFTs at once, this requires allocating scratch memory per thread, which is doable but I didn’t want to have to worry about that.
  2. I wanted the calculation to work completely in-place: it should be possible to write the outputs into the same memory that contained the inputs — that way without even needing a second buffer you can convert between time and frequency domains to do calculations, then convert back.
  3. At the API side, both the inputs and outputs should be in standard order (i.e. not bit-reversed). This requirement is true of most FFT algorithm implementations, but it’s worth calling out.
  4. Complex inputs (and outputs) also need to be packed complex numbers. That is, every pair of numbers in the input is a 2D real and imaginary pair (so the values are like "real0, imag0, real1, imag1, etc), and the same should be true of the outputs.
  5. I wanted to be able to make a single rotation table up-front for the largest-supported FFT size, where any smaller FFTs can use the same table as efficiently as if they had their own bespoke tables.
  6. I wanted it to be fast! It doesn’t have to be the fastest implementation out there, but it has to at least sit in the ballpark with the others.
Note

For completeness: the functionality I sacrificed to achieve the above goals is that it only supports power-of-two FFT lengths. At the very least, handling that would make point #5 quite difficult, as the tables tend to be more bespoke for arbitrary sizes due to having a larger variety of required rotations.

But I only needed to support power-of-two lengths for my use cases, so that’s all I did.

There are many FFT implementations out there, but there are very few that support all of these. Many of the fastest ones require scratch memory or some up-front computation to figure out the best way to do the algorithm.

My initial approach was to do a radix-4 decimation-in-frequency implementation with a bit-reverse pre-pass, with heavy SIMD optimizations for not only the computations through the middle, but also for the initial bit-reverse pass (which was written such that it could work in-place). This hit the first five points, but when I started timing it against others (specifically, the chowdsp FFT by Jatin Chowdhury, who wrote up a nice post about converting PFFFT to use AVX), it was about 20% slower! So, clearly I had work to do.

After some profiling, I noticed that the bit-reverse pass (even optimized as it was!) was taking up a large percentage of the runtime of the algorithm, so I started thinking about how to remove it (without losing the standard-in/standard-out ordering of the data).

But first, we could use a better understanding of how to do an in-place bit reverse.

Note

The following discussion is all predicated on power-of-two sizes. There are general ways to do the same tricks, but I didn’t need to implement them so I can’t speak to good ways to do them. I’ll leave that for someone else.

In-Place Bit Reversal

In our previous example code, we always did the bit reverse out-of-place (requiring separate input and output memory), but it turns out it’s possible to do it as a wholly-in-place algorithm.

Let’s arrange the indices (in both standard and bit-reversed orders) for a 16-element FFT in a grid, with labels along the top and left to show the memory indices:

There doesn’t seem to be a nice relational pattern here, but if we were to swap the middle two rows in both diagrams (note that we’re changing the view and not the memory ordering — this is the exact same data in memory as the previous set of diagrams), something becomes apparent:

Viewed this way, this is a matrix transpose! In fact, any power-of-four FFT length (as every power of 4 is also a square), can be viewed in this same way, by looking at the rows in bit-reversed order:

But what about a non-square length? This, interestingly, becomes two side-by-side matrix transposes:

Note

For purposes of describing the FFT-20XX algorithm, we don’t need to know the above fact, I just thought it was neat.

A nice thing about matrix transposes is that they can be done in-place (since every element — except the diagonals — simply swaps with another element). Here’s a bit of pseudocode to do this in-place bit reverse:

void BitReverseInPlace(complex[] data, int len)
{
  // fwiw there are fast ways to calculate this with
  // a known power of 2 using clz-style instructions.
  var rowCount = floor(sqrt(len))

  // For power-of-4 lengths this will equal
  // rowCount, otherwise it will be
  // rowCount * 2
  var colCount = len / rowCount

  for (var row = 0; row < rowCount; row++)
  {
    // using rowCount here because it's the size of
    // the square matrix
    for (var col = row + 1; col < rowCount; col++)
    {
      // The only difference from a standard square
      // matrix transpose, really, is that we're
      // bit-reversing the row indexing.
      var rc = BitRev(row * colCount, len) + col;
      var cr = BitRev(col * colCount, len) + row;
      Swap(data[rc], data[cr])

      if (rowCount != colCount)
      {
        assert(colCount == rowCount * 2)

        // Do the second side-by-side transpose.
        Swap(
          data[rowCount + rc],
          data[rowCount + cr])
      }
    }
  }
}
Note

There are, of course, more-efficient ways to do this. It is possible to make a nice cache-coherent, SIMD implementation of this (by using the same tricks people have found for doing standard matrix transposes), but we won’t actually need any of that.

With this understanding of how an in-place bit reverse might work, we can finally get to:

Eliminating the Bit Reverse Pass

So far, we’ve predicated all of the discussion around the FFT on the fact that the algorithm either takes inputs in standard order and outputs values in bit-reversed order, or (as we formulated all of the sample code) the other way around: with the inputs in bit-reversed order and the outputs in standard order.

But this is not strictly necessary.

Naturally, as with many things in computer science, there are people who worked on this exact problem over 40 years ago. One person who definitely went down this rabbit hole is (the now, sadly, deceased) Clive Temperton, who wrote the 1982 paper “Self-sorting mixed-radix fast Fourier transforms”.

Note

It’s always fun to find a computer science paper old enough that it was done on a typewriter!

When we first built up to the FFT algorithm way back in part 2, we noted that each step of the radix-2 FFT effectively does a deinterleave of the even and odd indices at that step, but also noted that doing an in-place deinterleave is a rough bit of work, so we’ll have to look for something else.

One thing we can note is, for a given FFT length NN, the index has log2 Nlog_2\,N bits, and thus there are ⌊log2 N2⌋\lfloor \frac{log_2\,N}{2} \rfloor bit reversals. For instance, a 4-bit index has 2 reversals (bits 0 ↔ 3 and 1 ↔ 2). A 5-bit index also has 2 reversals (0 ↔ 4 and 1 ↔ 3, with 2 remaining the same since it’s in the middle), 6- and 7-bit indices have 3 reversals, and so on.

Basically, with a radix-2 FFT, there are log2 Nlog_2\,N steps and half as many bit reversals (rounded down), so we could interleave single-bit reversals with the FFT steps.

There are two orders that the reversals can be done in. One way would be to start with the outer-most bits and work our way in towards the center-most bits.

Here’s the sequence of steps to do this for a 64-element FFT (note that we’re keeping the “matrix transpose” row ordering vs. natural memory ordering):

Each of these steps can be viewed as a collection of 2×2 matrix transposes:

  • The first one does sixteen 2×2 transposes of individual elements (every 2×2 block of elements)
  • The second does four 2×2 transposes, this time of 2×2 blocks (note the swap of the block containing “16, 48, 17, 49” and “2, 34, 3, 35”, for instance).
  • The final step does a single 2×2 transpose of 4×4 blocks (swapping the upper-right and lower-left quadrants).

The other order to do these in would be, instead, starting with the inner-most bits and going out from there (which I refer to, for purely comedic purposes, as the middle-out bit reversal):

They both end up with the same final result, and there’s not (at the moment) an obvious reason to prefer one over the other. Either way, any given step can take a 2×2 grouping of values and swap the elements on the diagonals, which we’ll leverage.

We now know how to break this up into individual steps, but when should we do those steps?

When To Do The Flippy Floppy

There are many ways we can choose to group the bit reversals together. There are five somewhat obvious choices:

  • Do them all at once at the beginning, before running the algorithm. This is what all the example FFT implementations in previous posts did.
  • Do them all at once, at the end. This is a post-pass in-place bit-reversal.
  • Because there are always half as many (rounded down) bit reversals as there are radix-2 passes, we could do them every other radix-2 pass (or, if we’re in radix-4 which has half the number of passes, once every radix-4 pass).
  • We could do one per radix-2 pass for the first half of the FFT, then past the halfway point, there are no more reversals to be done and everything proceeds using the standard algorithm for bit-reversed inputs.
  • We could do one per radix-2 pass for the last half of the FFT, so the first half would use the standard algorithm for standard-order inputs, before starting to swap things around.

Obviously the first two options there are what we’re trying to avoid (doing the whole thing as one big pass), so we have three (reasonable) choices. As a 16-element decimation-in-time (DIT) FFT using the middle-out bit reversal, the other three options would look something like the following (with the filled boxes denoting where we’re doing a bit reverse vs. a standard FFT algorithm step):

Note

The goal here isn’t to be able to trace every single reversal, it’s just to demonstrate how the bit reversals “sit” in between the radix-2 passes for the different orderings.

A butterfly diagram of a 16-element radix-2 FFT, where the inputs are in standard order. The first pass looks like normal, but then before the second pass there is a highlighted area representing the first bit reversal, where elements 2 and 3 swap with 4 and 5 (keeping their relative orders), and 10 and 11 swap with 12 and 13 in the same way. The rest of the elements remain unchanged through that section. After that is the next FFT pass, then another highlighted area, this one having elements 1, 3, 5, and 7 swap (keeping their relative orders) with elements 8, 10, 12, and 14. After that, the remaining two FFT passes proceed as normal, but unlike our other diagrams, the outputs are also in standard order, just like the inputs. " --> --> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7
First-Half Bit Reversal
An FFT diagram similar to the previous one, except the two bit reversal passes happen after the second and fourth FFT passes instead, evenly spaced (but in the same order relative to each other). --> --> 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4 0 0 4 4 2 2 6 6 0 2 4 6 1 3 5 7
Evenly-Spaced Bit Reversal
An FFT diagram similar to the previous two, except the two bit reversal passes happen after the third and fourth FFT passes instead. --> --> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4 0 0 4 4 2 2 6 6 0 2 4 6 1 3 5 7
Last-Half Bit Reversal

Ultimately, the algorithm we want is going to be doing things as radix-4, so the evenly-spaced one seems tempting. After all, there’s one reversal after each pair of FFT steps, which means there would be a single reversal for every radix-4 step.

However, if we visualize it as a radix-4:

A diagram of a 16-element radix-4 FFT with two FFT passes. Between the two passes is the first bit reversal, and after the second pass is the second (and final) bit reversal. Unlike every other FFT butterfly diagram we have had in this series, in this one the second pass inputs and outputs into each radix-4 computation are unevenly spaced. It looks kind of jumbled. --> --> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 4 6 1 3 2 3 6 9

Look at that second radix-4 step. Look at it. It’s weird. The nice, even spacing between radix-4 elements is completely gone, the relative angle indices are … scattered? And it just gets worse the larger the FFT sizes get.

It’s probably possible to make this work, but it seemed like a pain, and I don’t know how well it would play with CPU caches or SIMD.

That leaves either the first-half or last-half options, neither of which has that problem (they both, conveniently, keep the radix-4 steps even at each level).

Of the two, it turns out the last-half reversal has a nice property (shared by the DIF algorithm we came up with in the previous post): similar angles are grouped together longer, which means there are a number of optimizations we can apply to that formulation that we couldn’t do with the first-half version.

Note

The optimizations in this case include loading the angles outside of the inner-most loop and special-casing the first few sets of radix-4 passes, since we have a memory-coherent group with no rotations, then one with only 90-degree rotations, etc.

Also, it’s worth noting that it actually keeps the same sequence of butterfly strides (the spacing between subsequent inputs/outputs to the butterfly) that the standard algorithm has: each radix-2 pass has half the stride as the one before (which means each radix-4 pass has a quarter the stride of the one before). This makes the algorithm nice and regular to implement.

Note

The first-half reversal algorithm, by comparison, has a sort of “smaller then larger” layout where they roughly halve until the midpoint where they start doubling, ending with the same stride as the start.

You can see this in the diagram of it above.

So, that’s the core of FFT-20XX’s algorithm: radix-4, decimation-in-time, and with last-half bit reversal.

Now, we just have to figure out how to do said bit reversals.

How 2 Bit Reverse

As mentioned above, because we’re radix-4 we will need to do two bit reversals per radix-4 step in the last half.

Note

This is mostly true, with one exception: for sizes like 64, 1024, etc. where there are an odd number of bits that reverse, the first radix-4 of the back half (rounded up) only needs to do a single bit reverse since there’s an odd bit pair to swap.

Similar to how our example 1-bit-reverse-at-a-time squares above were the equivalent of doing a set of 2×2 matrix transposes, doing 2 bits ends up being the equivalent of doing a set of 4×4 matrix transposes.

The obvious way to do this would be to run the radix-4 FFT step, then do a separate pass that does the bit-reversal transposes. But we can do better — without requiring a separate pass over memory — by doing the bit reversals and the FFT step at the same time.

Here’s the beauty of the way this works: for any given radix-4 step with this method, the two bits that flip always correspond to the spacing between the radix-4 elements.

To explain what I mean by that, here’s a standard radix-4 diagram again. In last-half bit reversal world, the only two reversals in a 16-element FFT happen after the whole algorithm completes, so the diagram (without the reverses in it) is the same:

This is a standard radix-4 DIT FFT diagram, with the inputs in standard order and the outputs in bit-reversed order. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 2 4 6 1 2 3 3 6 9 0 0 0 0 0 0 0 0 0 0 0 0

Because we start from the middle bits and get to the outer bits last, the last radix-4 step will always be flipping the bits representing 1 and 2 (swapping them with the bits representing N2\frac{N}{2} and N4\frac{N}{4}, respectively), which will always be the spacing of elements in the last radix-4s (by this I mean, if you look at the first radix-4 of the last step, its indices will be 0, 1, 2, 3 — which is just every on/off combination of the bits for 1 and 2).

The next-to-last radix-4 step (for FFTs sized 256 and larger) involves the bits for 4 and 8. Note that, in our 16-element diagram above (which doesn’t have this bit reverse but still illustrates the point), the first radix-4 butterfly has indices 0, 4, 8, 12 which, like the previous example, is just every on/off combination of those two bits.

The step before that (for even larger FFTs) would involve flipping the bits for 16 and 32, with butterflies where the spacing is 0, 16, 32, 48.

This pattern continues happily no matter how large the FFT ends up being.

In the last step in our 16-element example, bit 1 swaps with bit 8 and bit 2 swaps with bit 4, and there just so happens to be a butterfly that starts at 4 and one that starts at 8.

What this means is: the smallest bits in a flip correspond to the spacing within a given radix-4 computation, and the largest bits in a flip correspond to the starts of radix-4 passes.

Thus, there are exactly four evenly-spaced radix-4 butterflies involved in every 4×4 transpose.

Here’s a diagram of four butterflies (A through D) in their input order, and their post-transform order, which is exactly what the bit reversal is doing (with some color highlighting to make the butterflies clearer):

So, for each radix-4 step that does a two-bit reversal, we can instead run four radix-4 butterflies at once, and then transpose the elements within them before writing them back out to memory, doing the whole thing in one read/write pass!

Note

Doing this can just barely fit within the 16 registers that x64 SIMD (pre-AVX-512) provides, with some trickery involved around when to load from and store to memory.

Final Algorithmic Details

There are two more details that need to be handled, before the algorithm is fully described.

First is, for non-power-of-four lengths, where do we put the single radix-2 pass?

This one has an easy answer: it can go anywhere in the first half! (If it were to go somewhere in the last half, it would mess up the nice alignment of radix-4 element spacing and bit reversals we were going over in the previous section).

For FFT-20XX, I ended up putting it directly after the very first radix-4 pass (as that first pass is nicely special- cased and optimized due to having no complex rotations).

Note

In fact, it was tempting to make the first pass a radix-8 pass, given that, in addition to the 8 complex components (16 values: reals and imaginaries), there only needs to be a single 22\frac{\sqrt{2}}{2} factor loaded, and it would avoid a whole pass over memory.

There wasn’t a way to get that all to fit in the 16 x64 SIMD registers (I was, annoyingly, able to get it down to needing 17 registers), and it ended up running slower — even at large FFT sizes — than just doing it as a radix-4 followed by a radix-2.

On ARM, however, where there are 32 registers to play with, this would probably work nicely!

Next, there’s the single-bit flip for FFT lengths with an odd number of bits that flip (for instance: a length of 64, which has 6-bit indices and thus 3 bits that flip, or 128 which has 7-bit indices which also has 3 bits that flip — with one that stays stationary in the middle).

It turns out this case is actually two cases: power-of-four and non-power-of-four FFT lengths.

For power-of-four lengths, we catch a nice break: the two bits that flip just so happen to be the middle two elements of each butterfly! For example, for a 64-length FFT, there are 3 radix-4 steps. The second step contains the single-bit flip, and the first radix-4 butterfly has indices 0, 4, 8, and 12. And it turns out that it’s the bits representing 4 and 8 that are flipping, so we actually only need to load a single radix-4 butterfly, then just write the inner two elements out in reverse order.

Nice!

For power-of-two lengths, we’re not that lucky. But it still only requires doing two radix-4 butterflies at a time, and the second and fourth values from one swap with the first and third values of the other (as there are two 2×2 matrix transposes within each pair of butterflies):

So here’s a rough breakdown of the whole algorithm:

  • For the first half (rounded down) of the radix-4 steps in the algorithm, proceed as normal, with the inputs in standard order.
    • Unimportantly, I put the radix-2 step after the first radix-4, just because it was easy.
  • If the FFT length has an odd number of bit flips:
    • If it’s a power-of-four length, do a pass just like a standard one, except where the middle elements of each radix-4 are written in reversed order, to do the single bit flip.
    • Otherwise, load the two relevant radix-4 butterflies, compute them both, then swap the second and fourth elements in the first with the first and third elements in the second before writing them out.
  • After that, each step loads four radix-4 butterflies at a time, computes all of them, then does a 4×4 matrix transpose of their elements (while still in registers!) and writes those out.

The devil, of course, is in the details (for instance, this simple description doesn’t go into the angle indexing — but it’s actually reasonably straightforward and regular!), but this is the high level of the algorithm!

Snark!

…if this many words can be described as just the “high level” overview of anything.

SIMD Considerations

This section will be light on specifics, but it’s worth going over a few of the SIMD considerations that went into the implementations.

The first thing is that, as mentioned in the requirements at the start of this post, the inputs and outputs to the complex FFT functions use packed complex numbers. For SIMD efficiency, the very first step does a deinterleave during its loads, to get a SIMD vector of all the reals and a second vector of all of the imaginary components for each.

As an example, for a 4-element SIMD type, it would load r0, i0, r1, i1, r2, i2, r3, i3 into two vectors:

  vR = r0, r1, r2, r3
  vI = i0, i1, i2, i3

Then, for intermediate steps, it stores those 8 neighboring values directly, without re-interleaving them (as they stay neighboring in blocks like that until the very end).

Only on the very last step does it re-interleave while writing the final results.

Next, because of the way the angles are arranged (with like angles grouped nicely together), each radix-4 SIMD butterfly only needs a single set of three angles (though, when doing two or four at a time due to the bit reversals, each butterfly has its own set of three angles, so for the double-bit-reversal case there are actually 12 angles, total).

Note

I’m saying 3 angles as that’s the canonical way, but on x64 it actually only does two angles, doing instead a “radix-222^2” computation and taking advantage of the speed of the FMA instruction, which allows it to do technically more calculations than the canonical version, but in less cycles.

I’ve mentioned it in previous posts, but this trick is nicely described in The ryg blog.

This stops being true right around the end of the process: the very last step (for all SIMD sizes) ends up requiring a SIMD set of distinct angles, as the grouping of the angles has finally gotten down to a single element (each butterfly in the final step has a unique set of angles).

Note

For larger SIMD sizes like AVX, the second-to-last step also needs to be special-cased, as it involves flipping bits 4 and 8. For AVX, for instance, each 8-element SIMD butterfly set contains two of the four radix-4 butterflies, in the first and last halves.

Finally, smaller FFT sizes tend to need to be special-cased. 8-element and smaller FFTs are just done in scalar (I doubt anyone is going to be perf-constrained by not having those tiny FFTs be SIMDed). And, for AVX’s 8-element vectors, 64-element and below will fall back on the SSE2 implementation.

The final pass also needs a different implementation for 2-element and 4-or-more-element SIMD vectors.

That’s Complex!

That is a hopefully-coherent rundown of how FFT-20XX’s complex-valued algorithm works! The algorithm itself isn’t that much more involved relative to a standard FFT implementation, but dropping the bit-reverse prepass (even after having heavily SIMD and CPU-cache optimized it) ended up getting FFT-20XX to be between 1.2 and 1.8x as fast as the chowdsp FFT that I was using as my baseline (tested at FFT lengths of 64 through 524,288), with the AVX implementation! (The SSE2 and NEON implementations end up 1.1 to 1.5x faster than chowdsp).

It hits all of the requirements: it works completely in place with no scratch memory needed, keeping the inputs and outputs in their natural order, and is fast (or at least, fast enough)! And it manages to do that all without an explicit bit-reverse pass!

Note

The inverse complex FFT, which I haven’t mentioned at all in this post, uses the same algorithm with the rotations reversed (switched via C++ templates), with the 1N\frac{1}{N} scale applied during the final radix-4 before saving the final results out.

In the next (and, thankfully, final) post in this series, we’re going to tackle the final boss of the whole project: the real-input FFT (and its inverse), which ended up being way trickier than I expected.

FFTs Part 4: The Inverse FFT

This is part 4 of a series of posts about FFTs and the specific algorithms that FFT-20XX uses.

  1. The Discrete Fourier Transform
  2. The Basics of the FFT
  3. Some Optimizations to the FFT
  4. The Inverse FFT (← you are here)
  5. The FFT-20XX Complex-Input Algorithm
  6. The FFT-20XX Real-Input Algorithm(s)

In the last post we looked at ways to make the core FFT algorithm more efficient. Before we (finally!) get to the actual FFT-20XX algorithm, it’s worth going over how the inverse FFT works. But to do that, we need to first take a detour into the decimation-in-frequency (DIF) FFT.

I hope you’re ready for some more diagrams because we’re about to dive in.

Note

In this post we’ll be focusing on radix-2 because it’s the simplest form to reason about, but all of this applies to other radixes as well.

Flipping Our Focus

Last time we started graphing the data flow of the FFT algorithm (using semi-standard butterfly diagrams). The radix-2 decimation-in-time algorithm ultimately ends up looking like this:

The diagram of a radix-2 FFT from the previous part, showing the four stages of the algorithm and how they interleave, with the input indices in bit-reversed order and the output indices in sorted order. " 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

If you remember back in part 2, we visualized the rotations for a length-8 FFT, and split things into even/odd inputs and first/last halves of the output.

We can, instead, visualize the same rotations, but switch to looking at even/odd outputs and first/last havles of the inputs (effectively transposing the breakdown we did before):

Note

I’m going to go through this faster than I did the first time, in the hopes that having already done a similar set of steps once, it’s clearer what’s going on this time.

Similar to part 2, we’ll group the evens and odds (this time, outputs instead of inputs), and make the rotations in the second half of the odd outputs be a negation of the first half’s rotations:

Now, we can note that for a given output, the first and last half inputs have the same rotations (i.e. inputs 0 and 4 have matching rotations, 1 and 5, etc), with the evens being summed and the odds being subtracted. We can pre-add (for the evens) and pre-subtract (for the odds) these to get two 4x4 blocks, first the evens, which is just a standard 4-element FFT:

Then the odds which, like in part 2, are a little bit different:

In this case, before doing the sub-FFT, we can rotate the inputs to the sub-FFT to get it in standard N2\frac{N}{2}-length FFT form:

This effectively puts the add/sub step first at each “level”, then the rotation afterwards (to feed into the next sub-FFT).

Because of the way that the divisions into sub-FFTs happen based on outputs rather than inputs, this results in a graph that looks like the DIT diagram, but flipped horizontally:

A diagram of a 16-element decimation-in-frequency FFT, showing the four "stages" of processing and how they interleave. The flow of the diagram and the angles are the same as the decimation-in-time version, but in reverse. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

Where decimation-in-time started with smaller sub-FFTs and then built up to the full one, each step of decimation-in-frequency instead does a computation pass on its inputs and then splits them up into sub-FFTs after, such that the last step of the radix-2 DIF is just a set of standard length-2 FFTs.

The computation pass is also different: rather than rotate the odd input before the addition and subtraction, DIF instead does the add/sub first then rotates odd output. This is why the rotation (twiddle) factors in the above diagram are on the right-hand side of the butterflies instead of the left.

Despite looking almost like its reversal, this actually computes the exact same outputs as the DIT FFT given the same inputs (ignoring floating-point error, for the pendantic. Yeah, I see you).

Note that, as formulated here, the diagram starts with the inputs in-order and ends with the outputs bit-reversed; this is a consequence of the alternate way we broke down the algorithm. It’s still possible to do the bit-reverse on the inputs so the outputs come out in-order, however. If we rearrange the inputs and outputs in the diagram accordingly, we get the folowing:

Diagram of a radix-2 decimation-in-frequency FFT, with the inputs in bit-reversed order and the outputs in natural (sorted) order, just like the original decimation-in-time diagrams. The angle indices in each stage are in bit-reversed order as a consequence of this reordering. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 4 2 6 1 5 3 7 0 0 4 4 2 2 6 6 0 0 0 0 4 4 4 4 0 0 0 0 0 0 0 0

Just to reiterate: the above two diagrams are functionally identical, it is simply a matter of visualizing them with different input/output orderings.

We now have enough information to turn this into a routine that — like the DIT version — does the bit reversal on the inputs before computing the result in-place. Here is some pseudocode:

void CalculateDFT(
  complex[] inputs,
  complex[] outputs,
  int len)
{
  if (len == 1)
  {
    outputs[0] = inputs[0]
    return
  }

  BitReverseCopy(inputs, outputs, len)

  for (int span = 2; span <= len; span *= 2)
  {
    for (int groupI = 0; groupI < len / span; groupI++)
    {
      var *data = &outputs[groupI * span]

      // We can pull the twiddle lookup/calculation
      // out of the innermost loop. Note the bit
      // reversal in the index lookup.
      var twiddle = Twiddle(BitRev(groupI, len), len)

      for (int k = 0; k < span / 2; k++)
      {
        int kOdd = k + span / 2

        complex even = data[k]
        complex odd  = data[kOdd]

        // Note the post-rotation here vs. the pre-
        // rotation that DIT does.
        data[k]    = even + odd
        data[kOdd] = (even - odd) * twiddle;
      }
    }
  }
}

This code is very similar to the DIT version; the main differences are the bit-reversed angle lookup and the rotation of the output of the computation pass instead of rotating the inputs (again, a consequence of doing the even/odd split on the outputs instead of the inputs).

Note

On systems without a fast fused multiply-add (FMA) instruction, this DIF formulation ends up being a really nice choice! However, there’s a trick using FMA mentioned in a note in part 3 (which is broken down nicely on The ryg blog) which, sadly, does not work with the DIF’s post-rotation.

A nice thing about the DIF formulated this way (with the bit reverse first) is that it lets the angle lookup move outside of the innermost loop (as you can see above). This is especially nice for radix-4 implementations where the table doesn’t store the 3k3k angles and they’re built via a multiplication, as the multiplication itself can move out of the inner loop.

The other interesting thing is that, with the angle lookups in bit-reversed order, you can store your table of rotations in bit-reversed order as well and, when stored this way, you automatically get nice cache-coherence for the smaller FFT types. If you look at the above butterfly diagram, the first angle is always 0, the second is always a quarter turn (it’s 416\frac{4}{16} in the above diagram, and for a length-8 FFT it would be 28\frac{2}{8}, which is equivalent), and so on. So with an arbitrarily-large FFT table, any given (power-of-2) sized FFT of length NN would just use the first N2\frac{N}{2} elements of the table.

Note

These properties are also true for DIT implementations where the bit reverse is done at the end instead of on the input.

That’s decimation-in-frequency! It ends up being a near-reversal of the way that decimation-in-time works, yet still computes the same result. Now that we’re through that, we can finally get to:

The Inverse FFT

Breaking a (time domain) signal down into its frequency components is pretty handy (you can use it to write cool visualizers, for instance!), but it’s even more useful if you can go from frequencies back into time-domain samples, letting you convert your audio into frequencies, manipulate them in some way (like an EQ) and then turn it back into samples that can be played back or encoded as normal.

The FFT (and the DFT in general) is really a linear system, which means it can be inverted, so we can make a transform that takes the output of an FFT and gives us the original inputs. This is the inverse FFT (IFFT).

To figure out how to do this, let’s start with the simplest useful case: a single DIT radix-2 pass (with an arbitrary angle kk):

Diagram of a 2-length FFT, showing the two inputs going into a single processing node, then back out to the two outputs. The second input node has a "k" representing the fact that it is rotated by an unspecified angle. 0 1 0 1 k

There are effectively two steps here:

  1. Rotate input 1 by kk.
  2. Add/subtract input 0 with the rotated input 1 to get the two outputs.

To invert this, we need to undo these two steps (in the opposite order as we did them).

Undoing the addition/subtraction is first, and this one is easiest to do algebraically. If we have these two equations:
 y0=x0+x1y_0 = x_0 + x_1
 y1=x0−x1y_1 = x_0 - x_1

We can solve them for x0x_0 and x1x_1 to get:
 x0=(y0+y1)/2x_0=(y_0 + y_1)/2
 x1=(y0−y1)/2x_1=(y_0 - y_1)/2

After that, we need to undo our initial step 1, which is the rotation by kk. Undoing a rotation is just rotating the same amount the other way, so that becomes a rotation by −k{-}k.

Note

Because a complex rotation value for a given angle looks like cos⁡ θ+i sin⁡ θ\cos\,\theta + i\,\sin\,\theta, the opposite rotation would be:
 cos⁡(−θ)+i sin⁡(−θ)\cos({-}\theta) + i\,\sin({-}\theta)

By the negative angle trig identites, this becomes:
 cos⁡ θ−i sin⁡ θ\cos\,\theta - i\,\sin\,\theta

So reversing the angle just means negating the imaginary component of the twiddle factor.

For a moment, we’re actually going to ignore that 12\frac{1}{2} scale on our result (just for now — we’ll get back to it), which ends up making the resulting 2-element inverse FFT steps look like:

  1. Add/subtract inputs 0 and 1 (the outputs from our forward FFT) to get two output values.
  2. Rotate the second output of the first step by −k{-}k.

This ends up looking like:

Diagram of a 2-length inverse FFT, showing the two inputs going into a single processing node, then back out to the two outputs. The second output node has a "-k" representing the fact that it is rotated by the opposite of the angle from the forward FFT. 0 1 0 1 -k

Which looks just like the DIF from earlier, except with the angle negated!

This continues to work as we scale the FFT up to larger sizes. Here it is as a 16-element inverse FFT:

A diagram of a 16-element inverted decimation-in-time FFT, which looks exactly like the earlier decimation-in-frequency diagram (with bit-reversed outputs), except all of the rotations are negated. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -0 -0 -0 -0 -0 -0 -0 -0 -0 -4 -0 -4 -0 -4 -0 -4 -0 -2 -4 -6 -0 -2 -4 -6 -0 -1 -2 -3 -4 -5 -6 -7

That’s right, by inverting the decimation in time FFT we end up with what looks like a decimation in frequency FFT with negated angles!

A Grumpy Aside

Honestly, I don’t actually like the “decimation-in-time/frequency” terminology, specifically because when using the same code for the inverse, it ends up being wrong: the DIT algorithm is decimating the inputs which are in time domain for a forward FFT, but they’re actually in frequency domain for an inverse FFT (since we’re going from frequency space back to time).

I would have preferred “decimation-in-input” and “decimation-in-output” but I don’t think I’m going to win a fight that I’m 60 years late to.

This relationship plays out the other way, as well: inverting the DIF gets a DIT-like FFT with negated angles:

A diagram of a 16-element inverted decimation-in-frequency FFT, which looks exactly like the earlier decimation-in-time diagram (with bit-reversed inputs), except all of the rotations are negated. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -0 -0 -0 -0 -0 -0 -0 -0 -0 -4 -0 -4 -0 -4 -0 -4 -0 -2 -4 -6 -0 -2 -4 -6 -0 -1 -2 -3 -4 -5 -6 -7

This is great, because it means the same routine (whether DIT or DIF) can be used for forward and inverse complex FFTs!

But, what about that 12\frac{1}{2} scale that we ignored earlier? Every (radix-2) step in the IFFT has that 12\frac{1}{2} scale on all of its outputs, so we can factor them all out of the inner steps and combine them into a single 1N\frac{1}{N} scale per output for the whole process!

Tiny Math!

The scale becomes 1N\frac{1}{N} because there are log⁡ N\log\,N passes, each with a 12\frac{1}{2} scale, and (12)log⁡ N=1N(\frac{1}{2})^{\log\,N} = \frac{1}{N}.

Thus, to use our (forward) FFT routine as an inverse FFT, there only need to be two changes:

  1. The twiddles need to have their sin⁡\sin components negated (to rotate by the opposite angle).
  2. Scale each resulting value by 1N\frac{1}{N} (where N is the FFT length).
    • This scale can be applied at the start or at the end, it doesn’t matter; it’s a constant scale to the whole result. You could even do it in the middle somewhere if you’re an absolute monster.

Here’s some pseudocode for this, which uses the same overall algorithm to compute either the forward or inverse FFT:

void CalculateFFT(
  complex[] inputs,
  complex[] outputs,
  int len,
  bool inverse)
{
  if (len == 1)
  {
    outputs[0] = inputs[0]
    return
  }

  BitReverseCopy(inputs, outputs, len)

  for (int subLen = 2; subLen <= len; subLen *= 2)
  {
    for (int subStart = 0; subStart < len; subStart += subLen)
    {
      var *data = &outputs[subStart]

      for (int k = 0; k < subLen / 2; k++)
      {
        int kOdd = k + subLen / 2
        complex evenSum = data[k]
        complex oddSum  = data[kOdd]

        // Get the twiddle factor and invert the imaginary
        // component for an inverse FFT to negate the rotation.
        var tw = Twiddle(k, subLen);
        if (inverse)
          tw.imag = -tw.imag

        oddSum *= tw
        data[k]    = evenSum + oddSum
        data[kOdd] = evenSum - oddSum
      }
    }
  }

  if (inverse)
  {
    // The inverse FFT needs to scale everything down
    // by the FFT length.
    float scale = 1 / len;
    for (int i = 0; i < len; i++)
    {
      outputs[i] *= scale;
    }
  }
}

We Made It!

This brings us (finally!) to the end of the “standard” breakdown of various FFT techniques. In this post, we looked at:

  • The decimation-in-frequency FFT, which is effectively a reversal of the flow of a decimation-in-time FFT.
  • The inverse FFT, which can be calculated the same as a forward FFT with the angles negated and with a constant scale.

In the next two posts, I’m going to go way off into the weeds and discuss the algorithmic variants that I used in FFT-20XX, starting with the algorithm for complex inputs.

FFTs Part 3: Some Optimizations to the FFT

This is part 3 of a series of posts about FFTs and the specific algorithms that FFT-20XX uses.

  1. The Discrete Fourier Transform
  2. The Basics of the FFT
  3. Some Optimizations to the FFT (← you are here)
  4. The Inverse FFT
  5. The FFT-20XX Complex-Input Algorithm
  6. The FFT-20XX Real-Input Algorithm(s)

In the last post we got to a basic implementation of the radix 2 decimation-in-time Cooley-Tukey algorithm. But there are still other additions and optimizations we can make before getting into the way FFT-20XX works. We’ll start by diving into the “radix 2” part of the algorithm: we can make improvements there.

Butterflies

Before we go into the specifics, I’m finally going to bring in a classic FFT diagram: the butterfly, an FFT data flow diagram. The most basic one is for a FFT of length 2, which has only a single step over two inputs. Here’s a diagram for the radix-2 decimation-in-time length-2 FFT (a 2-element version of the algorithm we derived in the previous post):

Diagram of a 2-length FFT, showing the two inputs going into a single processing node, then back out to the two outputs. The second input node has a "0" representing the fact that it is unrotated. " 0 1 0 1 0

In this diagram, the inputs are on the left, each computation (just one, in this example) is represented as a small circle, and the outputs are on the right. The computation (for a decimation-in-time FFT) rotates its second input (the odd input, which is the bottom one in the diagram) by the given rotation value; in this diagram the rotation is just a 00, but in general the value there will be some tt where the actual rotation angle is t/Nt/N clockwise turns (−2πt/N{-}2\pi t/N radians), where NN is the length of the FFT.

Note

The formatting of these butterfly diagrams is a little different than a standard butterfly diagram, which tend to look more like the following:

A classic-style diagram of a 2-element FFT, with a "w" component on the second input showing it rotates 0/2 times, then gets added to the first input for the first output and subtracted from the the first input for the second output. w 0 2 -1 0 1 0 1

These diagrams are more comprehensive (the wNkw^k_N value makes the fraction of k/Nk/N clockwise turns clear, where in my diagrams the “/N/ N” is implied), it has a −1-1 multiplier on the lower input going into the sum circle (to signify that the bottom “sum” is a difference), and the sums are each on their own line as opposed to a central circle that represents the add/subtract pair, but in practice — especially on lower-resolution displays — my variant is, imo, less visually noisy.

Plus, once you get into the higher radixes, even the standard diagrams start to be drawn more simply.

Now here’s one for the decimation-in-time length-4 FFT (where the bit reverse is performed on the input):

Diagram of a 4-element FFT, showing how the even inputs and odd inputs combine with each other in the same way the 2-element FFT's do, then how the results of those interleave to create the final outputs. 0 2 1 3 0 1 2 3 0 0 0 1

There are two “stages” in this radix-4 FFT (two runs of the outer loop of the code), which are separated via the vertical dotted lines. Really, though, this is four of the previous (length 2 FFT) butterflies bolted together, first with two separate 2-element computations (the first pass) followed by a single 4-element computation loop (the second pass, itself just two 2-element computations stacked on top of each other wearing a trench coat).

Finally, here’s a butterfly diagram for a full 16-element FFT:

A more complicated diagram of a 16-element FFT, showing the four "stages" of processing and how they interleave. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

There are four stages in this one (since log⁡2 16=4\log_2\,16 = 4), and note that you can still see the structure (discussed in the previous post) of eight 2-element computations in the first stage, then four 4-element computations in the next, then two 8-element computations, then a single 16-element computation. Also note the rotation angles in each stage: the last stage has rotations 0-7 (corresponding to 0/160/16 to 7/167/16 turns), the previous one has just the even numbers, the one before that just 0 and 4 (every other even value), down to no rotations in the first stage.

This is true in general (and if you look at the code we derived in the previous post, you can see the same relationship) where the last iteration has the most rotations, the next-to-last has half as many, and so on.

Now, here’s a diagram that we made in the previous post, showing a 16-element FFT in a sort of “index flow” way:

A diagram from the previous post showing the way the indices interleave at each step as they flow through the FFT. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 4 8 12 2 6 10 14 1 5 9 13 3 7 11 15 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Hopefully, the similarity between this diagram and the previous one is apparent: they’re diagramming the same process, but with different goals (the latter showing the indices flowing through the system, and the former showing the flow of values and the angles used to compute them).

So, now that we (hopefully) have an understanding of these diagrams and what they represent, it’s time to move on to the first optimization: a higher radix.

Doubling the Radix

We went with a radix-2 breakdown in the last post because it’s the most straightforward, but there are others. The one we’re going to focus on here is radix-4, which, in contrast to the above 16-element butterfly diagram, would instead look like the following (don’t worry about the specifics of the rotation values or what this four-in/four-out computation node is doing yet — we’ll get to that shortly):

A diagram of the same 16-element FFT as before, except this time as a radix-4 transform, with every 4 inputs combining together, then those combining in a second pass to generate the final outputs. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 0 0 0 0 2 4 6 0 1 2 3 0 3 6 9

The first things worth noticing here are that there are now half as many passes over the data, and each computation handles four values at a time instead of two.

This will end up being more efficient in a couple different ways. The main efficiency gain is that doing half as many passes means it halves the number of reads from and writes to memory, which as the FFT lengths get larger can make a big difference in how often there are cache misses. Second, it is possible to reduce the number of rotations needed by 14\frac{1}{4}, which can also make a difference on some CPUs (but not all, which we’ll get to).

To derive a radix 4 solution, you could go back to the original equation, split the inputs into four interleaved sections (where kmod  4k\mod 4 is 00, 11, 22, and 33 respectively), then split the outputs into quarters, and redo all of the rotation shenanigans that we did when deriving radix-2.

Nah. I’m not doing all that.

Instead, we’re going to start with the radix-2 diagram and build up to what that four-in/four-out computation looks like. Every pair of radix-2 passes can be turned into a single radix-4 pass, so let’s start by highlighting a couple such groupings in our radix-2 diagram:

The diagram of the 16-element radix-2 FFT again, but this time with the first two stages for the first 4 inputs highlighted in blue, then last two stages corresponding to outputs 2, 6, 10, and 14 highlighted in red, showing them both as being topographically the same, despite the spacing difference. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

Each of the groupings of “two pairs of radix-2 passes that all use the same 4 values” can be represented generically as:

A diagram similar to the earlier 4-element radix-2 FFT one, showing that inputs 2 and 3 get rotated by 2t, then the outputs of the inputs 1 and 3 computation get rotated by t and t + N/4 respectively before going into their final passes. '0' '2' '1' '3' '0' '1' '2' '3' 2t 2t t t+ N ― 4

Note the similarity between this and the 4-element butterfly diagram we made earlier: this is essentially just a generalized version of that.

The input/output indices are relative to the position in the FFT, but note that the middle two indices are in the opposite order as the output indices: this will always be true when we’ve done the bit reverse at the outset, and remains true no matter which intermediate step we’re on (i.e. it just automatically happens that way).

Also note that the angles themselves are relative, too: there will be some base angle tt that the other angles are relative to, and we’ll set it as the first angle in the second radix-2 pass (the tt just to the right of the middle line). As examples, in the first highlighed group at input indices 0, 8, 4, and 12, tt is 00, and in the second at output indices 2, 6, 10, and 14, tt is 22. Both angles in the first radix-2 pass are double this tt value (both labeled 2t2t), and the second angle in the last pass is always a quarter turn more than tt (labeled t+N4t + \frac{N}{4}).

To get from here to a full radix-4 computation, we can rearrange the angles a bit to get something equivalent:

Diagram of the same transform as the previous one, but with the angles rearranged. This time inputs 1, 2, and 3 get rotated by t, 2t, and 3t respectively, then the second output of the 1 and 3 transform gets rotated a quarter turn. '0' '2' '1' '3' '0' '1' '2' '3' 2t t 3t N/4
The Math

We do this by splitting the t+N4t + \frac{N}{4} apart at the addition, making it a rotate by tt then a separate rotation of N/4N/4.

We can then distribute the common rotation by tt back to the first stage and do them on inputs ‘1’ and ‘3’: input ‘1’ had no rotation so it ends up with a rotation of tt, and for input ‘3’ the tt combines with the 2t2t it already had to make a single rotation of 3t3t.

The N/4N/4 turn (a 90-degree clockwise rotation) can be done without any sine/cosine multiplications at all (it transforms a+iba + ib into b−iab - ia), so this is mathematically more efficient: it does 3 rotations on three inputs at the start of the process instead of 4 rotations split between the first and second inner radix-2 stages. The number of adds/subtractions remains the same, but that’s okay: there’s no way to reduce it any further.

This, then, is what becomes the computation node of the radix-4 butterfly diagram we made above! Here is the equivalent radix-4 diagram to the previous diagram (which hides the internal complexities, including the effectively-free quarter turn):

A 4-element radix-4 diagram showing the same t, 2t, and 3t rotations as the previous diagram, but instead as a single radix-4 process instead of 2 separate radix-2 passes. '0' '2' '1' '3' '0' '1' '2' '3' 2t t 3t
Note

An implementation detail worth mentioning here: on some systems using the first 4-element breakdown from above (the radix-2 one with the t+N4t + \frac{N}{4} term) can be more efficient! There are systems that have FMA instructions (the fused multiply-add) which have a cost close to doing either a multiply or an add by itself (x64 CPUs with the FMA extension — like most with AVX2 instructions — have this property). Doing it that way (which is sometimes referred to as radix-222^2), even with what seems like an extra complex multiply, can end up being cheaper due to less overall operations and one less required angle (the 3t3t angle isn’t required, using tt and 2t2t is sufficient).

There’s a breakdown of this trick on The ryg blog: Notes on FFTs: for implementers.

Here’s the 16-element radix-4 diagram we used earlier, with our same two radix-4 sections highlighted:

Diagram of a 16-element radix-4 FFT with the same corresponding "blue" and "red" highlighted paths as in the earlier radix-2 diagram. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 0 0 0 0 2 4 6 0 1 2 3 0 3 6 9
Note

This formulation of radix-4 is slightly different than the canonical one, which has a different “scrambled” input or output order from the bit reverse that we’re using. In that case, the reordered indices are reversed pairs of bits: for instance, an 8-bit binary value with bits 01234567 would becomes 67452301 instead of 76543210.

Instead, we’ve kept the radix-2 style bit reverse, the consequence of which is the reversal of the middle 2 inputs in the above diagrams (with reversed bit pairs, those would be in proper order, and the angles would instead be tt, 2t2t, and 3t3t, respectively).

Now, hopefully, it’s clear why the angle values are the way they are in this diagram. The first stage has no rotations (except for the effectively-free 90-degree rotation), and the second stage has four computations with increasing rotation values of the form 2t2t, tt, 3t3t.

The only issue with using the radix-4 algorithm is that it only fully works on FFTs with power-of-four lengths (because it splits in fours each time, so it works for length 4 but not 8, 16 but not 32, etc). The good news is that the way we’ve formulated it (by effectively smooshing together two radix-2 passes into a single radix-4 pass), you can just put a single radix-2 pass in there to make up the difference … and it doesn’t even matter where!

Here is a length-8 FFT where the first pass is still radix-2 but the second is radix-4:

Diagram of an 8-element FFT where the first pass is done as radix-2 and the last is done as radix-4. 0 4 2 6 1 5 3 7 0 1 2 3 4 5 6 7 0 0 0 0 0 2 0 1 0 3

And here’s the same length-8 FFT the other way around: radix-4 then radix-2:

Diagram of an 8-element FFT where the first pass is done as radix-4 and the last is done as radix-2 (the opposite ordering as the previous diagram). 0 4 2 6 1 5 3 7 0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 1 2 3

For longer FFTs, the radix-2 pass can be anywhere in the middle, as well - whatever is most efficient for your implementation! I found it easiest to place it right after the very first radix-4 pass (i.e. like that last diagram), mostly for simplicity.

Other Radix Flavors

So if radix 4 is more efficient than radix 2, that raises the question: are there other, even more efficient radixes? radix-8? radix-16? How far is too far?

Well, radix-4 is the largest power-of-two radix that has “free” rotations in the middle (that quarter turn). Radix-8 has some 45-degree-multiple rotations in the middle, which still require some multiplication. However, because both cosine and sine of 45 degrees (and related friends) are both 22\frac{\sqrt{2}}{2}, the multiply can be done as a common factor so it still is somewhat more efficient.

The problems with radix-8 tend to have to do with CPU register limits: you need to load 8 complex values (so 16 scalars), then (similar to how radix-2 needs 1 rotation and radix-4 needs 3) it tends to need 7 complex twiddles plus the 22\frac{\sqrt{2}}{2} internal value (so another 15 scalars) and you tend to also need some scratch registers as well to do computations. AVX and AVX2 only have 16 SIMD registers so even before you get to the angles you’ve already run out of register space. AARCH64 has 32, so you could maybe squeeze in there, but it would be tight. Plus you’re going to be up against CPU cache associativity for systems with eight-way associative caches, because you’re loading from 8 locations but also need to be loading the angles from somewhere.

Past radix-8, you’re out of register space, hitting CPU cache limits, and also have more internal rotations, so it’s going to perform way worse under most circumstances.

Note

One place where it’s really tempting to use radix-8, however, is on the very first decimation-in-time step, which has no twiddles (all seven of the twiddle angles are 0), and thus only has those nice-to-compute internal 45-degree rotations. However, the register limits are still an issue and, depending on how you have to load your values (i.e. for SIMD purposes you may want to do a deinterleave to separate the real and imaginary components), you may still not have enough register space. But it’s worth considering, if you can.

There is another radix option worth mentioning: the split-radix FFT algorithm, which I’m not going to detail here (because it’s complex and weird). In terms of required math operations, the split-radix algorithm gets you to some of the lowest-known possible operation counts. Unfortunately, in practice, I found that it breaks up the nice regularity of using just a standard radix-4 algorithm and ultimately — at least in my attempts at implementing it — had worse performance overall.

Okay, we’re through all of the radix shenanigans!

Lookup Tables

The last thing to touch on in this post is doing lookup tables for the angles. These tend to be exactly what they sound like: you precompute a table for your required FFT length that contains all of the sin/cos values needed for that length.

The simplest lookup table is one where you have N2\frac{N}{2} cos/sin values (00 turns through N2−1\frac{N}{2} - 1 turns), in order. However, there are some potential ways to make the table a little more efficient (with size, cache-friendliness, or both):

  • In many implementations, you don’t need both N2\frac{N}{2} cos⁡\cos and N2\frac{N}{2} sin⁡\sin values: because cos⁡(t)=sin⁡(π2+t)\cos(t) = \sin(\frac{\pi}{2} + t), you can store 3N4\frac{3N}{4} scalar values and start the cosine lookup partway into the table, and use 14\frac{1}{4} less memory.
  • If you’re doing radix-4, you can avoid storing the 3t3t angles and instead compute them using the tt and 2t2t rotations, which saves a bunch of table space. This may sound like you’re adding a complex multiply back in after eliminating it, but you can likely move that computation into an outer loop so it isn’t an issue.
  • It can also be convenient — for SIMD loads and CPU cache-friendliness — to store not only the angles in order for size NN, but to store all of the table sizes from some minimum length (like 4 or 8) up to your max length.
    • Doing this is nice because it means you can build a single table for your maximum required FFT length and it will perform just as well for any smaller FFT lengths as well.
    • Also, the earlier passes of the algorithm can take advantage of these smaller tables (the second radix-2 pass only needs the angles for a length-4 FFT, and the next only needs the angles for a length-8 FFT, etc). Loading from them can help with CPU cache coherence (as all of the required angles at that level are contiguous), plus SIMD loading if you need multiple angles within a single pass.

For FFT-20XX I found all of the above bullet points to be useful.

What Now?

No code this time, but using the above tricks (namely: using radix-4 instead of radix-2 where possible and switching to lookup tables for the rotations) gets you to a somewhat decent baseline FFT implementation! There are many more places to optimize: figuring out SIMD support and optimizing the bit reversal pass (or — spoiler alert — eliminating it altogether). We’ll get to those once we finally get into FFT-20XX’s algorithms.

Before that, next time, we’ll touch on the decimation-in-frequency version of the algorithm on our way to finally talking about the inverse FFT and how to compute it!

FFTs Part 2: The Basics of the FFT

This is part 2 of a series of posts about FFTs and the specific algorithms that FFT-20XX uses.

  1. The Discrete Fourier Transform
  2. The Basics of the FFT (← you are here)
  3. Some Optimizations to the FFT
  4. The Inverse FFT
  5. The FFT-20XX Complex-Input Algorithm
  6. The FFT-20XX Real-Input Algorithm(s)

Part 1 went through the core of how the discrete Fourier transform (DFT) works to turn a series of samples in time into a set of samples in frequency, and ended up with the following algoritm:

void CalculateDFT(
  complex[] inputs,
  complex[] outputs,
  int length)
{
  for (outIdx = 0; outIdx < length; outIdx++)
  {
    // Start the sum at 0.
    float sum = 0

    // This is the angular frequency (in radians/sample) for
    // the given output sample.
    float angularFreq  = -2 * pi * outIdx / length

    for (inIdx = 0; inIdx < length; inIdx++)
    {
      // Get the rotation value for the current input index
      // then use that to calculate the resulting rotation.
      float radians = inIdx * angularFreq
      complex rotation = cos(radians) + i*sin(radians)

      // A complex multiply with a unit complex vector is
      // a 2D rotation.
      sum += inputs[inIdx] * rotation
    }

    outputs[outIdx] = sum
  }
}
Note

A reminder: we’re going to be talking about these values as complex numbers (of the form a+iba + i b), but if you prefer, just think of them as a 2D vector instead ([a,b][a, b] where aa is the x coordinate and bb is the y coordinate).

We’ll be doing complex multiplication of these vectors with others, but in all cases a multiply like P⋅RP \cdot R will be a rotation of point PP by the angle that RR represents (where R=cos⁡ θ+i sin⁡ θR = \cos\,\theta + i\,\sin\,\theta).

This algorithm is O(N2)O(N^2), but there’s a much more efficient, O(N log⁡ N)O(N\,\log\,N) way: the fast Fourier transform (FFT) — and we’re going to derive it.

Note

The algorithm we end up deriving here is going to work specifically for FFT lengths that are powers of two, because it’s the easiest to implement (plus, to be honest, power-of-two lengths were sufficient for FFT-20XX so that’s all I implemented). The following techniques can be adapted for other lengths (i.e. if you need a length that is a mutliple of 3 or 5 or, I dunno, 97), plus there are ways to do this for arbitrary lengths (for instance: Bluestein’s algorithm). This series isn’t going to touch on any of those.

Halving the Work

The first step of deriving the FFT algoritm is figuring out where we can halve the amount of work. Since the DFT boils down to “every output takes every input multiplied by a rotation”, we can visualize all of the rotations as a 2D grid, where each column is an input and each row is an output.

Here’s a visualization of the rotations for an FFT of length 8 (adding a dividing line between the top and bottom halves, which should make sense in a moment):

Each rotation (as per the above pseudocode) for a given input index nn and output index kk is nk/Nn k/N turns (where NN is 8, the FFT length). But rotations are cyclical, and, for instance, turning a full turn (360 degrees) is equivalent to not turning at all.

We can use this cyclicity to our advantage! If you look at the even inputs (columns indexed 0, 2, 4, and 6), you’ll note that the rotations in the bottom half are identical to the top half. For instance, with input 2, outputs 0 and 4 are both unrotated, outputs 1 and 5 both rotate a quarter turn, and so on.

For the odd inputs (columns 1, 3, 5, 7), the angles aren’t the same. However, they’re still related: the bottom half rotations are always 180 degrees from the corresponding top half rotations. As an example, looking at the column for input 1, we see that output 4’s rotation is a half turn, where output 0 is unrotated — they’re facing away from each other. The other odd outputs are similar, with the bottom half rotations always pointing the opposite direction as their top-half counterparts.

In other words, the bottom half rotations of the odd inputs are negated versions of the top half (because with 2D vector A, Rotate(A, 180 degrees) is the same as the 2D vector -A).

Let’s rearrange the columns of the diagram to group the even and odd inputs together (evens to the left, odds to the right):

We can then rewrite the bottom-half odd inputs as negations of the top-half ones (note the minus signs in place of the usual plus signs):

Now all of the corresponding top and bottom half outputs use the same corresponding rotations per input; the only difference is that in the bottom half we subtract the rotated odd inputs instead of adding them. Our code, then, can switch to summing up all of the even and odd elements separately, then computing two outputs at once by doing evenSum + oddSum for the first (top) half of the outputs and evenSum - oddSum for the second (bottom) half, which means we’re now doing half the work as before!

Note

If you want this (and the next section) done algebraically instead of visually, the wiki page for the Cooley-Tukey algorithm has a fairly clear breakdown of the derivation of the whole thing.

Here’s what the code looks like if we do that:

void CalculateDFT(
  complex[] inputs,
  complex[] outputs,
  int length)
{
  // NOTE: Now looping over half the length
  for (outIdx = 0; outIdx < length / 2; outIdx++)
  {
    // Start the sums at 0.
    float evenSum = 0
    float oddSum = 0

    // angular frequency for the given output
    // (in radians/sample)
    float angularFreq  = -2 * pi * outIdx / length

    // NOTE: now incrementing by 2 to do odds and evens
    // separately.
    for (inIdx = 0; inIdx < length; inIdx += 2)
    {
      // Get the rotation value for the current input index
      // then use that to calculate the resulting rotation.
      float evenRads = inIdx * angularFreq
      complex evenRot = cos(radians) + i*sin(radians)
      evenSum += inputs[inIdx + 0] * evenRot

      // Do the same with the next index (inIdx + 1), for
      // the odd sum.
      float oddRads = (inIdx + 1) * angularFreq
      complex oddRot = cos(radians) + i*sin(radians)
      oddSum += inputs[inIdx + 1] * oddRot
    }

    // Computing 2 outputs in the same loop!
    outputs[outIdx]            = evenSum + oddSum
    outputs[outIdx + length/2] = evenSum - oddSum
  }
}

If you compare this code to what we started with, it does half the rotations and (roughly) half the adds (counting subtractions) as the original: the inner loop does effectively the same amount of work in both, but the outer loop runs half as much. Unfortunately, it’s not quite to O(N log⁡ N)O(N\,\log\,N) yet, so we need a way to effectively do this halving of work recursively.

Halving Work Again (and Again and…)

Let’s look again at just the first half of the outputs from our 8-length example:

If we look at just the even inputs for a moment, the pattern of rotations in that 4×4 block of the diagram ends up being the exact same pattern of rotations as for a standard 4-element FFT (half the size of our 8-element example):

Math Alert!

If you care about the algebra: this is because for each even rotation (nkN\frac{n k}{N}), kk is a multiple of 2. So if we say 2m=k2m = k, then the rotation becomes 2nmN\frac{2 n m}{N} which is equivalent to nmN/2\frac{n m}{N/2}, which is exactly how the angles for an FFT of length N/2N/2 would be specified.

This means that we can calculate the even sums recursively, computing the N/2N/2 even sums as if they were an N/2N/2-length DFT, which means we can do the same even/odd dance to halve its work as well.

That’s great for the even inputs, but what about the odd inputs? They have a similar pattern, but it’s not quite the same:

The first row is the same as in the 4-element DFT: no rotation. The second row, however, is different: each angle in the row is 1/8th of a turn rotated relative to the corresponding row of the 4-element DFT. The third and fourth rows are also different, with an extra 2/8th and 3/8th turn added to the angles in each row, respectively.

In other words, any given output kk’s odd inputs will have their rotations be k/Nk/N turns more than doing a standard N/2N/2-length FFT with those inputs.

Since “rotating every vector by t then summing” is the same as “summing then rotating by t” (that is, Rotate(A, t) + Rotate(B, t) equals Rotate(A + B, t)), we can calculate each odd sum by doing the work as a half-length DFT (like we can with the evens), then adjust each sum by rotating by its corresponding k/Nk/N-turn angle (called a twiddle factor, which is a fun name to say), like so:

Using that, we can now recursively calculate the even and odd sums using half-length FFTs, apply the twiddles, then do the add and subtract to get the final outputs.

Let’s write this as code again, this time recursively! To do this, for now we’ll use some temporary storage for simplicity:

// Helper function to build a complex
// rotation value
complex Twiddle(int k, int len)
{
  float angularFreq = -2 * pi * k / len
  return cos(angularFreq) + i*sin(angularFreq)
}

void CalculateDFT(
  complex[] inputs,
  complex[] outputs,
  int len)
{
  if (len == 1)
  {
    // To end the recursion, special-case
    // the 1-length FFT, which sums one input,
    // unrotated (i.e. it does nothing).
    outputs[0] = inputs[0]
    return
  }

  // Temp storage for the recursion
  complex[length / 2] evens
  complex[length / 2] odds

  // Separate the even and odd inputs
  for (k = 0; k < len / 2; k++)
  {
    evens[k] = inputs[2 * k]
    odds[k]  = inputs[2 * k + 1]
  }

  // Recurse into the even and odd FFTs
  // (each using the same array as input and
  // output, which is fine here)
  CalculateDFT(evens, evens, len/2)
  CalculateDFT(odds,  odds,  len/2)

  for (k = 0; k < len / 2; k++)
  {
    // Get the corresponding recursively-calcualted
    // sum from the relevant arrays.
    complex evenSum = evens[k]
    complex oddSum = odds[k]

    // The odd sum needs to be rotated by this
    // output's twiddle factor.
    oddSum *= Twiddle(k, len)

    // Now, as before, calculate two outputs from
    // these sums.
    outputs[k]         = evenSum + oddSum
    outputs[k + len/2] = evenSum - oddSum
  }
}

This is now truly, algorithmically O(N log⁡ N)O(N\,\log\,N)! We halve the work at each level of the FFT, which does way fewer rotations and adds than the initial DFT algorithm (for instance, the original algorithm for a 1024-length DFT would do around a million rotations, but this one does around five thousand).

But it’s not ideal: it’s recursive, and uses temporary storage per recursion. We can do better! But now we get into the “fun” that is…

Deinterleaving and Bit Reversal

To do all of this without recursion or scratch space, we need a way to do each level of the FFT calculation in-place. So let’s look at how data is flowing through the system.

Here’s a diagram of the routine (at a single recursion level) where, from left to right:

  • The inputs are deinterleaved into evens and odds.
  • Each of those two groups has a half-length sub-DFT performed on it (this is the recursion).
  • Those results are then used in pairs by each step of the computation loop to write corresponding pairs of outputs.
Diagram of the routine, which is laid out as described above. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Even DFT Odd DFT

If you look at the flow through this diagram, what’s interesting is that in the box on the right (representing the loop) each computation (one of the circles) pulls in from the same row that it writes out to (ignoring the actual index numbers). For instance, the top circle pulls in from indices ‘0’ and ‘1’, which are lined up perfectly with its outputs at ‘0’ and ‘8’.

This means that, theoretically, we could compute the entire FFT in-place (where the inputs and outputs are the same array), by doing the following:

  1. Deinterleave the data in-place (separating the evens and odds).
  2. Calculate the sub-DFTs recursively (again, in-place), using the first and last halves of the data as the even and odd sub-DFTs, respectively.
  3. Then, run the computation loop over the results, each iteration of which reads from and writes to the same elements, so no rearranging needs to take place.

That would look like the following — very much like the above code, except without the temporary evens and odds storage:

void CalculateDFTInPlace(
  complex[] data,
  int len)
{
  if (len == 1) return

  // A hypothetical function to do the
  // deinterleave.
  DeinterleaveInPlace(data, len)

  // Recurse into the even and odd FFTs
  // (first and last halves of our data)
  CalculateDFTInPlace(data, len/2)
  CalculateDFTInPlace(data + len/2, len/2)

  for (k = 0; k < len / 2; k++)
  {
    var kOdd = k + len / 2
    complex evenSum = data[k]
    complex oddSum  = data[kOdd]

    oddSum *= Twiddle(k, len)

    // Note that we're writing to the same
    // array indices that we read from!
    data[k]    = evenSum + oddSum
    data[kOdd] = evenSum - oddSum
  }
}

There’s one problem with this: it turns out, efficiently deinterleaving an array in-place is one of those problems that sounds like it would be super easy, but is instead kind of a nightmare!

Note

There are ways to do it, of course, even O(N)O(N) ways - but they don’t have particularly nice memory access patterns and end up not performing particularly well at larger sizes.

To try to avoid that, let’s keep investigating the pattern of data moves. We know that, in terms of data flow, the data into the last step comes in from two half-length sub-FFTs:

Diagram showing the even and odd 8-element sub-FFTs of a 16-element FFT, writing out to even and odd intermediate values (respectively), which then feed into the final step labeled "combine" which represents the final combination step. 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Even DFT Odd DFT Combine

If we were to track this pattern of deinterleaves all the way back to the lowest recursion level (the two-element FFTs), where the indices from right to left (from output to input) get deinterleaved at each step, here’s the ordering we end up with:

Compact diagram showing the inputs (ordered 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15) feeding into eight 2-element sub-FFTs, then those being fed in pairs into four 4-element sub-FFTs, each of which outputs the indices in a new order where the even/odd indices are interleaved. Each pair of those feeds into one of the two 8-element sub-FFTs which, again, outputs its input indices in interleaved order, then those two finally feed into the final 16-element FFT pass, which outputs the indices in the expected 0 to 15 sequential order. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 4 8 12 2 6 10 14 1 5 9 13 3 7 11 15 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

At a glance, the pattern of inputs on the left isn’t particularly clear, but it turns out it’s straightforward: the values are the original indices with their bits reversed!

As an example, for a 16-element FFT (like the diagrams above), we have 4 bits worth of index (since log⁡216  ⟹  4\log_2 16 \implies 4), so here’s the table of reversals:

0
0000
↔
0000
0
1
0001
↔
1000
8
2
0010
↔
0100
4
3
0011
↔
1100
12
4
0100
↔
0010
2
5
0101
↔
1010
10
6
0110
↔
0110
6
7
0111
↔
1110
14
8
1000
↔
0001
1
9
1001
↔
1001
9
10
1010
↔
0101
5
11
1011
↔
1101
13
12
1100
↔
0011
3
13
1101
↔
1011
11
14
1110
↔
0111
7
15
1111
↔
1111
15

As you can see, the ordering on the right of this table (0, 8, 4, 12, etc) is the same as the input ordering from the previous diagram and, in their bit representations, you can see that each index is just the 4 bits of the other reversed.

This is a much easier operation to perform than a deinterleave at each step, especially with separate input and output arrays! Here is a simple routine that does a bit-reversed copy from one array to another:

void BitReverseCopy(
  complex[] inputs,
  complex[] outputs,
  int len)
{
  for (int k = 0; k < len; k++)
    outputs[k] = inputs[BitRev(k, len)]
}
Note

The above code doesn’t have an implementation of BitRev, because an efficient implementation on many systems isn’t particularly readable; it turns into a sequence of swapping increasingly-large groups of bits until you reach the size of the int. For a C++20 implementaton, here’s a compiler explorer link.

Additionally, the above routine doesn’t work in-place, though it is totally possible to do so: a bit reversal can be written efficiently as a square matrix transpose (or two) if you get creative with the indexing of the “matrix” rows. However, the final FFT-20XX algorithms do not have an explicit bit reversal step, so I’m not going to go into those details. Sorry!

Going Iterative

We now have all of the pieces we need to assemble the final algorithm. Let’s go back to this earlier diagram of the data flow for a 16-element FFT:

The same diagram of the flow of indices through a 16-element FFT that we saw earlier. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 4 8 12 2 6 10 14 1 5 9 13 3 7 11 15 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Each column of boxes in this diagram corresponds to a level of recursion in our original code (recursing from right to left because the recursion is done before the computation): the last column (with the one tall box) is the top of our recursion stack, which then recurses into its two sub-DFTs (the next column to the left), and so on, until we reach the left-most column which is the lowest level of recursion.

Each box represents a computation pass at its given recursion level (the loop in the above code).

If the inputs have been pre-bit-reversed (so that they’re in the order specified on the left-hand side of the above diagram), then each of the boxes reads from and writes to the same element indices, so each computation (box) acts in isolation.

Rather than doing this recursively, we can instead treat each of the columns of this diagram as a single pass through the data!

More specifically for this diagram, it takes the inputs in what we now know to be bit-reversed order, and does four (log⁡216\log_2 16) passes on the inputs (where, again, each pass represents a level of recursion in our example code):

  • The first pass does eight 2-element computation loops
  • The next pass does four 4-element loops
  • Next is two 8-element loops
  • Lastly, a single 16-element loop to get the final outputs
Note

In each of the above passes, the number of computation loops multiplied by the number of elements in the loop is 16 (8×28\times2, 4×44\times4, 2×82\times8, and 1×161\times16), which means each pass processes NN elements. Since there are log⁡2 N\log_2\,N passes of NN elements each, this algorithm — like the recursive one — is our target O(N log⁡ N)O(N\,\log\,N).

This process can (finally!) be done iteratively instead of recursively, by getting the elements into the expected bit-reversed order, then modifying each element in place, in passes:

void CalculateDFT(
  complex[] inputs,
  complex[] outputs,
  int len)
{
  if (len == 1)
  {
    // Special case length 1.
    outputs[0] = inputs[0]
    return
  }

  // Do the bit reversal so we can do the rest
  // iteratively in the outputs, in-place.
  BitReverseCopy(inputs, outputs, len)

  // Outer loop iterates all of the subFFT lengths:
  // starting at 2, then doubling until we reach the
  // full length ... this is log2(len) iterations.
  // This is equivalent to each level of recursion in the
  // previous code example.
  for (int subLen = 2; subLen <= len; subLen *= 2)
  {
    // This loop iterates over each subsection, as the starting
    // index into the data (this is the individual sub-DFTs in
    // the previous example).
    for (int subStart = 0; subStart < len; subStart += subLen)
    {
      // The data for this subsection starts at subStart.
      var *data = &outputs[subStart]

      // Finally, do the computation loop for this subsection.
      // The logic here is unchanged from the previous code
      // examples, and, as with our deinterleave case, reads
      // and writes to the same pairs of elements.
      for (int k = 0; k < subLen / 2; k++)
      {
        int kOdd = k + subLen / 2
        complex evenSum = data[k]
        complex oddSum  = data[kOdd]
        oddSum *= Twiddle(k, subLen)
        data[k]    = evenSum + oddSum
        data[kOdd] = evenSum - oddSum
      }
    }
  }
}
Note

The bit reversal does not necessarily have to come at the beginning: the algorithm could instead be written to take the inputs in natural order and end up with the outputs in bit-reversed order, then do the bit reversal in-place as the last step. The indexing within the passes would be different, but the algorithm would otherwise work the same.

What we’ve ended up with is the radix-2 decimation in time Cooley-Tukey algorithm. It’s radix-2 because each “recursion” splits into two sub-FFTs, and it’s decimation in time because each pass deinterleaves the input, time domain samples.

Note

If you go back up to the rotation diagrams again, you might note that the rotations are diagonally symmetrical, which means you could instead split on even/odd output for the first and last half of the inputs (instead of the other way around, like we did). This will end up as a similar but different algorithm, and is the decimation in frequency version of an FFT, which we’ll get to in a later post.

Room for Improvement

While we’ve now gotten to the core FFT algorithm, this still isn’t anywhere near an optimal implementation, and there are a number of things we’ll want to do to get this even faster. For instance:

  • As mentioned above, this is a radix-2 algorithm, but there are other radixes (such as radix-4, where each FFT splits into 4 sub-FFTs) that are more efficient and worth investigating.
  • The sines and cosines could be done via a lookup table instead of calculating them at runtime, since for a given FFT length there are only so many unique angles that are required.
  • Doing the bit reverse pass to get things into the correct order (either at the start or end) can be a sizeable chunk of time, and depending on implementation can wreak havoc on your CPU’s caches.
  • And then there’s doing SIMD optimizations and otherwise trying to make the memory accesses CPU-cache-friendly.

We’ll touch on the first couple of those next time!


(thanks again to Neintonine for giving some feedback before it went live!)

FFTs Part 1: The Discrete Fourier Transform

Because the world clearly doesn’t already have enough of them, I recently released a new fast Fourier transform (FFT) library: FFT-20XX. To the best of my ability to tell, it uses an algorithm that is at least slightly novel, and I thought it might be interesting to write about it.

This is the first of a series of posts about FFTs and (eventually) the specific algorithms that FFT-20XX uses:

  1. The Discrete Fourier Transform (← you are here)
  2. The Basics of the FFT
  3. Some Optimizations to the FFT
  4. The Inverse FFT
  5. The FFT-20XX Complex-Input Algorithm
  6. The FFT-20XX Real-Input Algorithm(s)

As a first step I thought it might be fun to start with “what even is the discrete Fourier transform?”

Fourier Transforms

Any explanation of a Fourier transform would be remiss to not include a link to this fabulous 3Blue1Brown video that nicely illustrates how the Fourier transform works. I highly recommend watching it!

This post, however, is specifically about the discrete Fourier transform (referred to as the DFT), which is a Fourier transform that operates on sampled data (like, say, digital audio or images) instead of continuous data. The FFT (fast Fourier transform) is the standard algorithm used to compute the result of a DFT — we’ll get to it in the next post.

What Does the DFT Even Do?

Any periodic signal (i.e. a signal that repeats, such as looped audio) can be represented as the sum of a set of sine waves at different frequencies. Here is an example of a simple signal that can be broken down into three waves:

Diagram of a somewhat complex wave, which is composed of the three following waves
=
Diagram of the lowest frequency and highest-amplitude wave that makes up the above complex wave.
+
Diagram of the middle frequency wave that makes up the above complex wave. It has an amplitude lower than the first component wave.
+
Diagram of the highest-frequency wave that makes up the above complex wave. It has a lower amplitude than the first two.

This is true of any periodic signal whether it is analog or sampled — no matter how complex it may seem.

The DFT answers a simple question: given a set of samples that represents a periodic signal, which frequencies are represented in that signal?

Note

The “periodic signal” bit is important! The algorithm assumes that the block of samples it is processing repeats forever:

Diagram showing a signal that repeating three times.

However, this won’t be the case for all blocks, such as this one where there’s a hard discontinuity:

Diagram showing a signal that repeats three times, however this time the wave in each signal do not line up properly at the edges, causing a discontinuity.

This can cause noise in the resulting DFT output. There are a few tricks that can be done for cases like this (like windowing the signal) to effectively “pretend” that it is periodic when it’s not, but that’s out of scope for this post.

To put it another way: the DFT converts a signal that is made up of samples in time (where each sample represents a point on the signal at a given time) into the same signal represented in frequency (where each sample represents the amplitude (how tall the wave is) and phase (the side-to-side position of the wave) of its corresponding frequency). These two representations are frequently referred to as time domain and frequency domain, and both encode the same signal in different ways.

Note

There is also an inverse DFT (the IDFT) which converts the other way — from the frequency domain back to the time domain. Many signal processing applications convert from time to frequency space to do some operation, then use the inverse DFT to convert back. We’ll get to the inverse DFT in a later post.

For a given repeating signal that is N samples long, the DFT returns contribution values for N frequencies, each with one more cycle than the previous. To put it a different way: for each frequency with index k (starting at 0 and ending at N - 1) there are k cycles of a wave (so index 0 has 0 cycles, index 1 has 1 cycle, etc).

Here are the 8 waves for a DFT with 8 samples (the red wave with circles is the cosine and the green wave with squares is the sine):

0
Diagram of Frequency 0: all of the cosine values are '1' and all of the sine values are '0'. There are 8 points on each wave representing the samples (this is true for all subsequent waves as well).
1
Diagram of Frequency 1: there is a single up to down to up cycle of the cosine and sine waves.
2
Diagram of Frequency 2: there are two up to down to up cycles of the cosine and sine waves.
3
Diagram of Frequency 3: there are three up to down to up cycles of the cosine and sine waves.
4
Diagram of Frequency 4: there are four up to down to up cycles of the cosine and sine waves. Notably, the cosine samples alternate between '1' and '-1', and the sine samples are all '0'.
5
Diagram of Frequency 5: there are five up to down to up cycles of the cosine and sine waves.
6
Diagram of Frequency 6: there are six up to down to up cycles of the cosine and sine waves.
7
Diagram of Frequency 7: there are seven up to down to up cycles of the cosine and sine waves.

Ultimately, a DFT will give you a set of values that tell you how much each of these frequencies contributes to the signal. Specifically, each frequency will have a value that represents both its amplitude and its phase.

Note

The frequency at index 0 always has cosine values of 1 and sine values of 0, and this ends up measuring how “off-center” the signal is (relative to the x axis). This is known as the DC bias or DC offset.

A signal with no DC bias. The wave is centered on the x axis
No DC bias
A signal with positive DC bias. The wave is above the x axis
Positive DC bias
A signal with negative DC bias. The wave is below the x axis
Negative DC bias

Let’s figure out how to calculate the DFT for a signal!

Frequency Testing

The first step of computing the DFT is to figure out how to get a single frequency out of a signal. Ignoring phase for a moment, this can be done in a surprisingly straightforward manner (to me, at least): if we multiply each sample in the signal by the cosine value of the test frequency and sum the results, you end up with a value that represents the contribution of that frequency to the signal (which is 0 if the frequency is not present in the signal).

Here is an interactive example where you can set the signal and test frequencies and see the result of this process. For purposes of illustration, we’ll display the average instead of the final sum (as the sum would be too large to fit in the diagram):

An interactive diagram that demonstrates how the signal and test waves are processed to detect frequencies. × Interactive diagram = avg →
Signal Amplitude:
1.0
Signal Cycles:
2
Test Cycles:
2

Note that when the frequencies match (signal and test cycles), the resulting average scales with the amplitude of the signal, otherwise (with one exception we’ll touch on in a moment) it is 0. This makes this sum effectively a frequency detector (again, ignoring phase for now)! This is still true even when there are multiple frequencies represented within the signal: this will result in a zero value for frequenices that are not in the signal and non-zero values for those that are.

Math Time!

If you’re interested in the math of how this works, here you go:

The sum of all samples of a repeating cos⁡ x\cos\,x signal is 00, as it has the same area above and below the xx axis, which cancels out in the sum.

Now, if we multiply two such waves together: cos⁡ x⋅cos⁡ y\cos\,x \cdot \cos\,y, this can be rewritten (via trig identities) as:
 12[cos⁡(x−y)+cos⁡(x+y)]\frac{1}{2}[\cos (x - y) + \cos(x + y)]

If xx and yy don’t match, these are just two repeating cosines, and each of them sums to 00 over all of the samples (just like the single wave above).

However if x=yx = y, this becomes:
 12[cos⁡(x−x)+cos⁡(x+x)]\frac{1}{2}[\cos (x - x) + \cos(x + x)]   ⟹  12[cos⁡ 0+cos⁡ 2x]\implies \frac{1}{2}[\cos\,0 + \cos\,2x]
   ⟹  12+12cos⁡ 2x\implies \frac{1}{2} + \frac{1}{2}\cos\,2x

That remaining cos⁡\cos term, over all of the samples, once again sums to 0, which leaves us with a constant 12\frac{1}{2} in the average.

As noted, there’s an exception here, where the multiply-and-sum seems to register a match when it shouldn’t. For example: if you set the Signal Cycles to 1 and the Test Cycles to 15 (or vice versa), it will have a non-zero average even though the frequencies don’t match. In fact, with the exception of frequencies 0 and 8, there are two matches for every other frequency. Why is that?

Well, now it’s time to talk about…

Aliasing and Negative Frequencies

Let’s take a closer look at the cosine values for our example frequencies of 1 and 15 cycles:

1
Diagram of the cosine for frequency 1 with sixteen samples. The wave has a single cycle.
15
Diagram of the cosine for frequency 15 with sixteen samples. The wave has fifteen cycles. The sample positions in this diagram are exactly the same as in the diagram of frequency 1.

Note that while the waves are different frequencies, the cosine samples are the same! This is because of aliasing, which is where a frequency above the maximum representable frequency ends up sampling as if it were a different, lower frequency.

The frequency above which aliasing occurs is called the Nyquist frequency, which is the highest frequency where there can be both a high and low sample for every cycle (you need both to represent a wave). In a signal with N samples, that frequency has N / 2 cycles. For example, with 16 samples the Nyquist frequency has 8 cycles (which you can see have a clear up then down pattern):

Diagram of the cosine for frequency 8 with sixteen samples. The wave has eight cycles. Every sample on the cosine wave alternates between '1' and '-1'

Above this frequency, the cosine samples end up aliasing to a lower frequency and cannot be differentiated anymore. Here are some more example pairs of aliased cosines from our 16-sample example:

2
Diagram of the cosine for frequency 2 with sixteen samples. The wave has two cycles.
14
Diagram of the cosine for frequency 14 with sixteen samples. The wave has fourteen cycles. The sample positions in this diagram are exactly the same as in the diagram of frequency 2.
3
Diagram of the cosine for frequency 3 with sixteen samples. The wave has three cycles.
13
Diagram of the cosine for frequency 13 with sixteen samples. The wave has thirteen cycles. The sample positions in this diagram are exactly the same as in the diagram of frequency 3.
7
Diagram of the cosine for frequency 7 with sixteen samples. The wave has seven cycles.
9
Diagram of the cosine for frequency 9 with sixteen samples. The wave has nine cycles. The sample positions in this diagram are exactly the same as in the diagram of frequency 7.

Note that each pair has matching cosine samples, despite the different wave. Specifically: with a repeating sample count of N, any frequency with N−kN - k cycles has the same cosine values as the frequency with kk cycles (that is 1 matches 15, 2 matches 14, etc).

Note

This is just like the optical illusion where rapidly-spinning things like car wheels can appear to be rotating backwards.

That’s neat! But it’s not the whole picture. We can’t just look at the cosine values, we need to look at what happens to the sine values as well:

1
Diagram of the sine for frequency 1 with sixteen samples. The wave has a single cycle.
15
Diagram of the sine for frequency 15 with sixteen samples. The wave has fifteen cycles. The sample positions in this diagram are like the ones in the diagram of frequency 1, but negated.
2
Diagram of the sine for frequency 2 with sixteen samples. The wave has two cycles.
14
Diagram of the sine for frequency 14 with sixteen samples. The wave has fourteen cycles. The sample positions in this diagram are like the ones in the diagram of frequency 2, but negated.
3
Diagram of the sine for frequency 3 with sixteen samples. The wave has three cycles.
13
Diagram of the sine for frequency 13 with sixteen samples. The wave has thirteen cycles. The sample positions in this diagram are like the ones in the diagram of frequency 3, but negated.
7
Diagram of the sine for frequency 7 with sixteen samples. The wave has seven cycles.
9
Diagram of the sine for frequency 9 with sixteen samples. The wave has nine cycles. The sample positions in this diagram are like the ones in the diagram of frequency 9, but negated.

While the cosines are the same in these pairs of frequencies, the sines are negated and appear vertically flipped! This means that a given frequency with N−kN - k cycles has negated sine values from the frequency with kk cycles.

The relationship here is that the aliased frequencies in each pair are negated versions of the other, since cos⁡(−a)=cos⁡(a)\cos({-}a) = \cos(a) and sin⁡(−a)=−sin⁡(a)\sin({-}a) = {-}\sin(a). Thus, frequency N−kN - k has the same angle as the hypothetical frequency at −k{-}k:

Cosines:

-1
Diagram of the cosine for a hypothetical frequency -1 with sixteen samples. The wave has a single cycle.
15
Diagram of the cosine of frequency 15 with sixteen samples. The wave has fifteen cycles. The sample positions in this diagram match the ones in the cosine diagram for hypothetical frequency -1 exactly.

Sines:

-1
Diagram of the sine for a hypothetical frequency -1 with sixteen samples. The wave has a single cycle, negated vs a standard sine wave.
15
Diagram of the sine of frequency 15 with sixteen samples. The wave has fifteen cycles. The sample positions in this diagram match the ones in the sine diagram for hypothetical frequency -1 exactly.

In practice, when computing the DFT, the frequencies above Nyquist are referred to via their negative indices instead of as the positive aliased ones.

This explains why all of the frequencies in the above example (except DC and Nyquist) have two matches: the cosines match at both the positive and negative versions of the angle. This may seem redundant, but it isn’t always — we’ll get into why in a bit.

Note

It’s also worth noting that the multiply-then-average in the example diagram results in half the signal amplitude for each match, and when both are summed, the result represents the full amplitude!

However, DC and Nyquist — because they each only have a single match — have an average that matches the amplitude exactly.

Measuring Phase

So far we have been looking at a signal that contains a cosine, comparing it with a test wave that is also a cosine, and getting an amplitude-relative result. But the original description of the DFT mentions both amplitude and phase as being represented, so what happens if we let the phase of the signal shift around relative to the test?

An interactive diagram that demonstrates how adjusting the the signal phase affects the average. × = Interactive diagram avg →
Signal Phase:
0.0

Oh no! Sliding the phase around causes the resulting average to oscillate! While we get the expected 0.5 average when the phase is 0, it is -0.5 at a phase of 0.5 (a half-wavelength offset) and, even worse, 0 at phases of 0.25 and 0.75 (quarter- and three-quarter-wavelength offsets)! Clearly there is something else we need to consider here…and it turns out it’s the sine of the test frequency.

Instead of just multiplying by the cosine of the test value, we can instead multiply by both cosine and sine to get two values per sample. If we then treat those two resulting values as a 2D coordinate (where cosine corresponds to x and sine to y), we can average them all to get our final result, which will be at the origin for non-matching frequencies and at some non-origin position for matches.

Note

“Multiply by both sine and cosine” is a simplification for purposes of illustration. It works for now but is not the general form, which we’ll get to in a bit.

An interactive diagram that demonstrates how adjusting the the signal and test waves affects a 2D average. × Interactive diagram = avg → Amp: 0.5 Phase: 0.00
Signal Phase:
Signal Cycles:
Test Cycles:

Some observations from this diagram:

  • If the cycle value magnitudes don’t match, the points are all evenly distributed around the center (and thus the average is at the origin). This makes it much easier to visualize why we end up with no measured amplitude for mismatched waves.

  • If the cycle value magnitudes do match (i.e. a signal of 2 cycles with either 2 or -2 test cycles), the points are off-center, and thus their average is also off-center.

  • Increasing the phase causes the resulting average to spin clockwise when the test cycle count is positive, but counter-clockwise when the test cycle count is negative. The magnitude of the average remains the same no matter the phase.

  • At Nyquist (8 cycles), the resulting points always lie on the x axis, as the test wave’s sine values are all zeros. It turns out: a phase-shifted wave at Nyquist is indistinguishable from a non-shifted wave with scaled amplitude (because there is literally no way to represent such a phase shift with the given sample rate).

This gives us a new way to think about this computation: rather than thinking of the operation as a multiplication, instead we can think of each sample of the signal being rotated by the angle of the test wave at that sample position to get a new 2D position. Those 2D positions are then summed to get a value that corresponds to the frequency’s contribution.

The computed amplitude (the strength of this frequency’s contribution) is the magnitude of the resulting average (its length), and the phase is the angle of the average (computed, in this case, using atan2).

2D Coordinates and Complex Numbers

Each result of this multiplication with cosine and sine ends up as a 2D coordinate. Canonically, the Fourier transform represents these as a complex number (of the form x+i⋅yx + i \cdot y). Why complex numbers? Honestly I think it’s a hack to get a 2D coordinate that is simple to represent with standard math notation (mathemeticians, don’t @ me).

Note

If you, like me, prefer 2D vectors to complex numbers, just pretend that x+iyx + iy is the 2D vector [ x   y ][\,x\,\,\,y\,] as you read all of this: the real component is the xx coordinate and the imaginary component is the yy coordinate.

To be fair, complex numbers do have a nice property that standard 2D vectors do not: they can be multiplied in a meaningful way.

The specific complex multiplications done by the DFT (an input sample [a+iba + ib] multiplied by a wave value [cos t+i sin tcos\,t + i\,sin\,t]) ends up rotating the input by the angle tt!

Note

If you’re familiar with matrices and linear algebra, this complex multiply (with cc and ss representing the cosine and sine values):

(x+iy)⋅(c+is)(x + iy) \cdot (c + is)

  ⟹  (xc−ys)⋅i(xs+yc)\implies (xc - ys) \cdot i(xs + yc)

…results in exactly the same operations as multiplying a 2D vector (x, y) with a 2x2 rotation matrix representing the same angle:

[xy]⋅[cs−sc]\begin{bmatrix}x & y\end{bmatrix} \cdot \begin{bmatrix} c & s \\ -s & c \end{bmatrix}

  ⟹  [xc−ysxs+yc]\implies\begin{bmatrix} xc - ys && xs + yc \end{bmatrix}

This also finally gives us an answer to the earlier question of why we need both the positive and negative versions of a given frequency: if the input samples are complex (i.e. 2D) instead of purely real-valued (1D), the contributions to these paired frequencies can be different, and both are needed to fully reconstruct the signal.

For real-valued signals, however, the paired results will be complex conjugates, where the result (a+iba + ib) for frequency kk is the conjugate of the result for frequency −k{-}k: (a−iba - ib); they have the same real (x) term but opposite imaginary (y) terms.

When summed, these values (a+iba + ib and a−iba - ib) become 2a2a as the imaginary components cancel out, which is how a signal made up of real cos⁡\cos terms and imaginary sin⁡\sin terms can be a purely real-valued signal.

Note

It’s worth pointing out something that shows up in the standard formula for the DFT: mathematical notation has an absolutely wild shorthand for cos⁡ t+i sin⁡ t\cos\,t + i\,\sin\,t:

eite^{it}

That’s right, taking the mathematical constant ee to an imaginary power is the same as a rotation around the origin. Why? Well, 3blue1brown has an explanation if you’re curious.

Personally I don’t like this shorthand because it obscures the meaning of the equation, especially for non-mathemeticians (which is, if I’m doing my calculations right, most people).

Calculating the DFT

Okay, we finally have all of the pieces of how to calculate a DFT, it’s time to put them together.

A DFT takes a set of complex input samples in the time domain and produces the same number of complex output samples in the frequency domain, where the first output sample (at index 0) represents the DC offset, the middle one (at index N/2) represents the Nyquist frequency, and the rest are either the positive or negative angles in between.

There are a couple minor (but important) differences in the value calculation done in the above interactive diagrams vs how the DFT does them:

  • Typically the DFT rotates the opposite direction as the above diagrams (i.e. using sin⁡(−t)\sin({-}t) instead of sin⁡ t\sin\,t), so the rotations actually spin the opposite way (clockwise becomes counter-clockwise and vice versa).
  • Rather than averaging the results of these rotations, the DFT simply sums them — no division by N is performed.

Otherwise, the process described above can be used to get the contribution of any single frequency within the signal, so then we just need to do this process for every possible frequency in the signal.

Thus, here we are, finally at some pseudocode to calculate the DFT:

void CalculateDFT(
  complex[] inputs,
  complex[] outputs,
  int length)
{
  for (outIdx = 0; outIdx < length; outIdx++)
  {
    // Start the sum at 0.
    float sum = 0

    // This is the angular frequency (in radians/sample) for
    // the given output sample (the "test frequency" from the
    // earlier examples).
    float angularFreq  = -2 * pi * outIdx / length

    for (inIdx = 0; inIdx < length; inIdx++)
    {
      // Get the rotation value for the current input index
      // then use that to calculate the resulting rotation.
      float radians = inIdx * angularFreq

      // `i` here is the imaginary unit
      complex rotation = cos(radians) + i*sin(radians)

      // A complex multiply with a unit complex vector is
      // a rotation.
      sum += inputs[inIdx] * rotation
    }

    outputs[outIdx] = sum;
  }
}
Note

As mentioned in a previous note, the standard formulation of the DFT uses an exponential shorthand (which I do not like) to represent the rotation. Thus, the DFT is written in standard mathematical notation as:

Xk=∑n=0N−1xn⋅e−i2πkNnX_k = \displaystyle\sum_{n = 0}^{N - 1} x_n \cdot e^{-i2\pi\frac{k}{N}n}

…which is equivalent to the above pseudocode.

We’ve finally done it! We have some code we can use to calculate the DFT for a given signal.

The above algorithm is O(N2)O(N^2), which may seem like the best that can be done. However, there’s a bit of algorithmic trickery that can be done to get that down to O(N log⁡ N)O(N\,\log\,N), which is considerably more efficient. That trickery is the fast Fourier transform (FFT), and the next post will go into the details of how that works!


(thanks to Neintonine, zerostride, and Chuck for giving me some great feedback on this before it went live!)