Skip to content

Is there interest in an alternative FFT implementation supporting Bluestein's algorithm for near-prime sizes? #11885

Closed

Description

@mreineck

If there is interest, I could provide an FFT library implemented in C99 that is based on fftpack, but falls back to Bluestein's algorithm for near-prime lengths. Accuracy should also be better than the original fftpack.

You can have a look at the code at https://gitlab.mpcdf.mpg.de/mtr/pocketfft

I can contribute this under the 3-clause BSD license, but I haven't added the necessary file headers yet.

Activity

  1. matthew-brett commented on Sep 5, 2018

    @matthew-brett
    Contributor

    That sounds interesting ... I guess it would need an expansion of tests to make sure those cases had been properly covered?

  2. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    Doesn't numpy already test these cases? I mean, they are supported in principle, they are just very, very slow.

  3. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    In any case, testing FFTs is fortunately really straightforward, so if additional tests are required, they should be trivial to add.

  4. seberg commented on Sep 5, 2018

    @seberg
    Member

    Don't trust such numpy test parts. This is code that has not recieved significant updates for years and years and the test coverage rules were not always as stringent.
    So yes, it should very good test coverage, plus code coverage tools (but numpy CI might help with that).

  5. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    OK, I just ran a quick coverage test with my own unit tests using "gcov", and the only lines not touched are in the function for reporting a fatal error :)

    However I don't have any idea how to integrate this into the numpy CI ... I'm not really a Python person.

  6. ncgeib commented on Sep 5, 2018

    @ncgeib

    I am strongly in favor of replacing the FFTPACK implementation in numpy. The accuracy for real-valued FFTs and large prime sizes is so bad, in principle, it produces wrong results. At first glance, the pocketfft implementation looks good to me, but I know little of C and the conditions on it required by numpy.

    I also note that the same accuracy problem exists in scipy. This issue should be fixed once and for all for both packages. In the long term one FFT implementation should be deprecated and removed.

    @mreineck Do you know how the speed compares to the original fftpack and/or numpy's fftpack? I noticed that the C implementation in numpy is slower than the Fortran one in scipy. We should make sure we are at least not slower.

  7. matthew-brett commented on Sep 5, 2018

    @matthew-brett
    Contributor

    If you make a PR with the C code, I can help with the tests.

  8. seberg commented on Sep 5, 2018

    @seberg
    Member

    I think we still require C89, but not quite sure. But even if, I guess it should be pretty easy to fix those things.

  9. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    If you make a PR with the C code, I can help with the tests.

    I'll do that, but I won't be able to provide the Python->C glue.
    (Well, I can try, but think this may be a job for experts.)

  10. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    I think we still require C89, but not quite sure. But even if, I guess it should be pretty easy to fix those things.

    I sure hope not! Changing this code back to C89 would be really painful.

  11. matthew-brett commented on Sep 5, 2018

    @matthew-brett
    Contributor

    Hum - I suppose our problem will likely be Visual C++ 2008.

  12. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    @mreineck Do you know how the speed compares to the original fftpack and/or numpy's fftpack? I noticed that the C implementation in numpy is slower than the Fortran one in scipy. We should make sure we are at least not slower.

    If there is a difference, pocketfft should be slightly faster than the original fftpack code for highly composite lengths, and very much faster for near-prime lengths.
    However, much depends on how the benchmark is actually set up. For example, are the twiddle factor computations included in the FFT run time? How often do we expect an FFT to be executed once its twiddle factors have been computed, etc.

  13. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    Hum - I suppose our problem will likely be Visual C++ 2008.

    I just read that for this compiler it is possible to just declare the code as being C++, which is fine with the C99 subset I'm using (i.e. I'm not using "complex").

  14. matthew-brett commented on Sep 5, 2018

    @matthew-brett
    Contributor

    I think that VC++ 2008 is our least capable requirement, so I think that will work. But I'd love to hear from someone who knows this stuff better than me.

  15. mreineck commented on Sep 5, 2018

    @mreineck
    ContributorAuthor

    I just checked ... code compiles flawlessy as C++98 with g++ (if I #define the restrict keyword away).
    I don't have access to Microsoft platforms, however.

  16. 18 remaining items

  17. grlee77 commented on Jan 18, 2019

    @grlee77
    Contributor

    pyfftw monkeypatches scipy (and numpy IIRC)

    I would say pyFFTW can be used to monkeypatch numpy or scipy, but it doesn't do so by default. I tend to just import the needed functions from pyfftw.interfaces.numpy_fft or pyfftw.interfaces.scipy_fftpack. These two match the API of numpy.fft and scipy.fftpack, respectively.

  18. mreineck commented on Jan 18, 2019

    @mreineck
    ContributorAuthor

    Otherwise does anything speak against using pretty fast fft

    Unfortunately it only supports a very limited subset of transform lengths.

  19. mreineck commented on Apr 5, 2019

    @mreineck
    ContributorAuthor

    Time to close this?

  20. rgommers commented on Apr 5, 2019

    @rgommers
    Member

    Indeed:)

  21. rgommers commented on Apr 5, 2019

    @rgommers
    Member

    Otherwise does anything speak against using pretty fast fft which is a modernization of fftpack (essentially adding translating fftpack to C and adding SIMD instructions), which has supposedly pretty good performance.

    I had a quick browse: it's pretty old, not really maintained, and 1-D only so not relevant.

  22. mreineck commented on Apr 20, 2019

    @mreineck
    ContributorAuthor

    I had some more time to work with the code, and have come up with a (still experimental) Python package based on pocketfft: https://gitlab.mpcdf.mpg.de/mtr/pypocketfft

    This package has the following features:

    I think this could be a nice candidate for use in numpy and scipy, but there are also a few caveats:

    • The interface is similar, but not identical to numpy.fft; I don't support the s argument because it makes the code structure much more complex. If truncation/padding is required, this would have to be done before the FFT call. Normalization is done by passing an explicit normalization factor instead of a string argument; this is nore flexible.
    • The code is heavily templated C++ and uses pybind11 for interfacing; this means that a C++14-capable C++ compiler is required.

    I'd be happy to post benchmarks, if anyone is interested. Are there any established multi-D FFT benchmarking tools for Python?

  23. rgommers commented on Apr 21, 2019

    @rgommers
    Member

    nice @mreineck, looks pretty clean

    The interface is similar, but not identical to numpy.fft; I don't support the s argument because it makes the code structure much more complex. If truncation/padding is required, this would have to be done before the FFT call.

    This is a good choice I think, it's kind of weird to have s (or n in the case of np.fft.fft) in the API.

    The code is heavily templated C++ and uses pybind11 for interfacing; this means that a C++14-capable C++ compiler is required.

    The Windows situation is a bit unfortunate. C++14 needs MSVC 19.0, which we won't get before Python 3.9 I think. It's possible that compiling extensions with a newer MSVC against a Python compiled with an older MSVC is now feasible, but I haven't seen it tried yet.

    I'd be happy to post benchmarks, if anyone is interested. Are there any established multi-D FFT benchmarking tools for Python?

    No benchmarks that I know of. Yes, a benchmark would be nice to see if it's not too much work:)

    In SciPy we will very likely get a GSoC project to deliver a backend system this summer. That would allow connecting pypocketfft as an option, perhaps on Linux and macOS only.

  24. mreineck commented on Apr 22, 2019

    @mreineck
    ContributorAuthor

    This is a good choice I think, it's kind of weird to have s (or n in the case of np.fft.fft) in the API.

    Very glad to hear that! The only place where this cannot be entirely avoided is irfftn, where the code cannot deduce the size of the last axis unambiguously.

    No benchmarks that I know of. Yes, a benchmark would be nice to see if it's not too much work:)

    Here is something very ad hoc. Given a dimensionality and maximum extent of the array, it runs several random-sized FFTs with both numpy and pypocketfft and plots a histogram of the run-time ratios.

    Here are a few results from a laptop with an AVX-capable CPU:
    1d
    2d
    3d

    The speed-ups in the 1D case are not due to vectorization, but due to smaller calling overhead on the Python side. As you can see, some transforms have become slower; I'm not sure yet why that happens (the 1D pocketfft code is more or less unchanged), but I'll investigate.

    In higher dimensions the improved performance is explained partially by vectorization and partially by avoiding the explicit array transpositions that numpy currently carries out.

    When switching to single precision, the speedup becomes more prominent:

    1d_single
    2d_single
    3d_single

    Here is the code, so you can test on other architectures:

    # Don't run this benchmark with numpy<1.17 ... it will probably take ages!
    
    import numpy as np
    import pypocketfft
    from time import time
    import matplotlib.pyplot as plt
    
    
    def bench_nd_fftn(ndim, nmax, ntry, tp, nrepeat, filename=""):
        res=[]
        for n in range(ntry):
            shp = np.random.randint(1,nmax+1,ndim)
            a=(np.random.rand(*shp) + 1j*np.random.rand(*shp)).astype(tp)
            tmin_np=1e38
            for i in range(nrepeat):
                t0=time()
                b=np.fft.fftn(a)
                t1=time()
                tmin_np = min(tmin_np,t1-t0)
            tmin_pp=1e38
            for i in range(nrepeat):
                t0=time()
                b=pypocketfft.fftn(a)
                t1=time()
                tmin_pp = min(tmin_pp,t1-t0)
            res.append(tmin_pp/tmin_np)
        plt.title("t(pypocketfft / numpy 1.17), {}D, {}, max_extent={}".format(ndim, str(tp), nmax))
        plt.xlabel("time ratio")
        plt.ylabel("counts")
        plt.hist(res,bins="auto")
        if filename != "":
            plt.savefig(filename)
        plt.show()
    
    bench_nd_fftn(1, 8192, 1000, "c16", 10, "1d.png")
    bench_nd_fftn(2, 2048, 100, "c16", 2, "2d.png")
    bench_nd_fftn(3, 256, 100, "c16", 1, "3d.png")
    bench_nd_fftn(1, 8192, 1000, "c8", 10, "1d_single.png")
    bench_nd_fftn(2, 2048, 100, "c8", 2, "2d_single.png")
    bench_nd_fftn(3, 256, 100, "c8", 1, "3d_single.png")
    
    
  25. insertinterestingnamehere commented on Apr 22, 2019

    @insertinterestingnamehere
    Contributor

    The code is heavily templated C++ and uses pybind11 for interfacing; this means that a C++14-capable C++ compiler is required.

    The Windows situation is a bit unfortunate. C++14 needs MSVC 19.0, which we won't get before Python 3.9 I think. It's possible that compiling extensions with a newer MSVC against a Python compiled with an older MSVC is now feasible, but I haven't seen it tried yet.

    Minor aside here: I think pybind11 supports MSVC 2015. This may not be a huge issue. From what I've seen in practice, the partial C++14 support there gets you pretty far. Using later compilers is supposed to be possible now too, but I don't know what the details of shipping the runtime libraries, etc. would look like.

  26. mreineck commented on Apr 22, 2019

    @mreineck
    ContributorAuthor

    That sounds encouraging! I can try to dial back the used C++14 features to a minimum.

    One thing I'm using is aligned_alloc() (which apparently was only standardized in C++17...), but it should not be a big deal to replace that with posix_memalign(), if that is more readily available on Windows.

    I definitely will need help with testing on Microsoft platforms, since I'm not using them myself.

  27. mreineck commented on Apr 22, 2019

    @mreineck
    ContributorAuthor

    I forgot to mention that vectorization is done by means of the gcc vector extension syntax (https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html). I verifed that this works fine with gcc and clang (should also work with icc, but I couldn't test this yet); for MSVC this might have to be disabled, but the scalar part should work fine.

  28. insertinterestingnamehere commented on Apr 22, 2019

    @insertinterestingnamehere
    Contributor

    For aligned allocation in MSVC 2015/2017 you need to use _aligned_malloc and _aligned_free. I'm not sure what to do about the vector extensions though. MSVC has its own vector extensions, but the syntax is different and I haven't used them enough to offer much help there.

  29. mreineck commented on Apr 26, 2019

    @mreineck
    ContributorAuthor

    Some updates:

    • Intel icpc apparently doesn't understand all of the gcc vector extensions. I tried with version 19.0, and it was unhappy about mixed simd-scalar operations. So no vector support for Intel at this time.
    • I added in-place support to the functions where this makes sense (fftn, ifftn, hartley). If this is selected, the result will be placed into the input array. For 1D transforms this is probably not a big gain, but in the multi-D case it can make a big difference in memory consumption.
  30. mreineck commented on May 6, 2019

    @mreineck
    ContributorAuthor

    Added an interface that provides r2c/c2r transforms in the style of scipy.fftpack.[i]rfft().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions