Repository navigation
Abstract FFT interface - #2093
Conversation
Change `_fft_wrap` to delay function specification. The goal being one can create custom wrappers for different external FFT implementations. This both keeps Dask flexible in the area of FFTs without necessarily adding many implementations.
Create public API FFT wrapper functions and make use of them to wrap the exist NumPy FFTPACK interface used by Dask. Also provide some brief explanation of how this API works in the docstrings.
Even though we are already doing this wrapping internally in Dask and implicitly testing. We should make sure explicitly that it works in case the implementation in Dask changes in the future.
As another exercise of the wrappers, test wrapping SciPy's FFTPACK to make sure our wrappers apply just as well to it.
| takes a function that behaves like ``numpy.fft.ihfft``. | ||
| """ | ||
|
|
||
| return _fft_wrap(np.complex_, _ihfft_out_chunks)(fft_func) |
There was a problem hiding this comment.
Perhaps instead of defining a new wrapper for each type, define a single function that dispatches on the type? Something like:
ifft = fft_wrapper(npfft.ifft, kind='ifft') # Could maybe use a better keyword name
hfft = fft_wrapper(npfft.hfft, kind='hfft')
...There was a problem hiding this comment.
I'm 50/50 on it. What's the disadvantage of the current form?
There was a problem hiding this comment.
Just a lot of functions. I'm slightly in favor of a smaller public interface and a more concise implementation. Not a big deal though, current way is fine as well.
There was a problem hiding this comment.
Well, I'm planning to add the 2-D and N-D versions of these too. So as long as we don't think that this will make the function too long with such a big branch that is fine. Though some linting tools may balk at this.
There was a problem hiding this comment.
I'm also in favor of fewer functions here if we can manage it. It makes it easier to maintain and change in the future if need arises.
|
|
||
| ifft = ifft_wrapper(spfft.ifft) | ||
| assert_eq(ifft(darr), spfft.ifft(nparr)) | ||
| assert_eq(ifft(darr2, axis=0), spfft.ifft(nparr, axis=0)) |
There was a problem hiding this comment.
As SciPy doesn't have hfft or ihfft, we can't wrap those.
Also they implement rfft and irfft, but how they handle the data is a bit strange. Instead of returning or taking complex values all of these functions return real values that split the imaginary part from the real part. So wrapping them would be kind of a pain as we would have to massage the data back into the expected form in the wrapper.
There was a problem hiding this comment.
Perhaps it doesn't matter as long as fft_wrap ensures that the dask.array version is consistent with whatever function it is passed. We don't need to test against numpy, we just need to test against the function that we were given.
There was a problem hiding this comment.
So I think it is worth testing that the computation is correct. Otherwise we have no idea whether the wrapper is behaving correctly from the test side.
|
Given you wrote the original implementation, @cowlicks, it would be good to hear your feedback on this. |
| assert not same_keys(fft(darr, 5), fft(darr, 13)) | ||
|
|
||
|
|
||
| def test_wrap_numpy(): |
There was a problem hiding this comment.
Can we refactor this to use pytest.mark.parametrize? This might make it easier to extend in the future.
@pytest.mark.parametrize('module', [np.fft, scipy.fft])
@pytest.mark.parametrize('funcname', ['fft', 'ifft', 'rfft', ...])
def test_wrapper(module, funcname):
try:
func = getattr(module, funcname)
except AttributeError:
pytest.mark.skip()
dfft = fft_wrapper(module, funcname)
assert_eq(fft(nparr), dfft(darr))There was a problem hiding this comment.
Also I have a slight preference to use names like x and dx rather than nparr. These names were probably from before, but this refactor might be a nice chance to rename them.
There was a problem hiding this comment.
Can we refactor this to use
pytest.mark.parametrize?
Probably to some extent. Though I don't think we can lump everything into one test. Please see this note.
There was a problem hiding this comment.
Is the PyFFTW library consistent with the numpy interface?
There was a problem hiding this comment.
These other variables were already defined and use in the other tests. I used them to be consistent and to ensure the wrappers were doing the correct thing. I would like to keep this change focused on the task at hand.
There was a problem hiding this comment.
I don't know what the legality is when you're testing against other code.
There was a problem hiding this comment.
IANAL. That said, my understanding was as long as the GPL dependencies are optional and are not shipped with the distribution, this should not effect licensing. This SO answer seems pertinent.
Note: FFTW is GPL 2.
There was a problem hiding this comment.
That being said, if you would rather steer clear, I'm ok with that. It is part of the reason I designed these to be user accessible wrappers as opposed to discussing optional FFTW support. 😄
There was a problem hiding this comment.
Have parameterized the tests. Have not done anything with pyFFTW. We can save that for a follow-up PR.
There was a problem hiding this comment.
FWIW here is a PR ( #2105 ) that tests against pyFFTW. Though feel free to accept or decline the patch as you see fit.
| return map_blocks(partial(fft_func, n=n, axis=axis), a, dtype=dtype, | ||
| chunks=chunks) | ||
| return map_blocks(partial(fft_func, n=n, axis=axis), a, dtype=dtype, | ||
| chunks=chunks) |
There was a problem hiding this comment.
It is useful to avoid partial. map_blocks can accept keyword arguments, I recommend the following:
map_blocks(fft_func, a, n=n, axis=axis, dtype=dtype, chunks=chunks)
There was a problem hiding this comment.
This line was already here. I have merely indented it. While there may be improvements that can be made to this function, I'd like to keep this change compact.
|
👋 @jakirkham I haven't touched dask in a while, so I'll defer to @mrocklin and @jcrist cheers! |
Instead of having a variety `*fft_wrapper` functions, simply provide one `fft_wrapper` function that takes a specification as to the kind of FFT function that is being wrapped.
07ac953 to
f675878
Compare
|
Ok, I think I have addressed the concerns raised with this patch. Would appreciate another review. |
| elif kind == "hfft": | ||
| return _fft_wrap(np.float_, _hfft_out_chunks)(fft_func) | ||
| elif kind == "ihfft": | ||
| return _fft_wrap(np.complex_, _ihfft_out_chunks)(fft_func) |
There was a problem hiding this comment.
Would be nice to raise a ValueError in case the kind is unknown.
There was a problem hiding this comment.
In the spirit of keeping code as data when possible, I recommend creating a dict like
{'fft': _fft_out_chunks,
'ifft': _fft_out_chunk, # also should this be ifft?
....
}There was a problem hiding this comment.
I recommend creating a dict like
We could do that. So a different dict for type too?
There was a problem hiding this comment.
Would be nice to raise a
ValueErrorin case the kind is unknown.
Handled and added a test.
There was a problem hiding this comment.
I recommend creating a dict
Also done. Made a dict with the parameters so they can be passed as kwargs.
| try: | ||
| func = getattr(fft_mod, funcname) | ||
| except AttributeError: | ||
| raise SkipTest() |
There was a problem hiding this comment.
Use pytest.skip('fft method missing') # or a better message here instead of raising SkipTest
There was a problem hiding this comment.
Ok, not super familiar with pytest. So thanks for the pointer. Will update.
|
Other than my comments above, this looks good to me. Thanks for the fix @jakirkham. |
| def func(a, n=None, axis=-1): | ||
| if len(a.chunks[axis]) != 1: | ||
| raise ValueError(chunk_error % (axis, a.chunks[axis])) | ||
| def _fft_wrap(dtype, out_chunk_fn): |
There was a problem hiding this comment.
Can we auto-detect the dtype by calling the function on a length zero array? Actually, we may be able to just ignore the dtype argument altogether and let map_blocks take care of this (it will call the function on a length one array of the input array's dtype?
There was a problem hiding this comment.
If we know the dtype ahead of time, I don't see a good reason not to provide that information statically if it's cheap to do.
There was a problem hiding this comment.
I do like your idea about detecting type better, @mrocklin. Let me give that some more thought.
There was a problem hiding this comment.
In the past, I have not seen a great way to go from float* to complex* that preserves precision (e.g. float32 to complex64). So have wound up handling this myself. I think from complex* to float* this should be easier (e.g. take real of 0 or similar), but the other way around ends up being kind of ugly.
To cutdown on the amount of boilerplate in the tests, use `pytest.mark.parametrize` so as to cycle through many different combinations. This should keep the code small while allowing us to try various combinations of NumPy and SciPy FFT functions with the wrappers.
f675878 to
c1b8f41
Compare
If an unknown kind is provided to `fft_wrapper`, raise a `ValueError` explaining that this happened.
To simplify passing parameters to the wrapper, create a dictionary that has all of the parameters for each supported kind so that they can be easily passed through.
Explain the function's expected API more clearly. Also note the supported kinds of functions that can be wrapped and how they should be specified.
3711e60 to
68538ab
Compare
Combine the remaining NumPy tests into the single parameterized test for FFT wrappers. Also as SciPy's FFTPACK implements `rfft` and `irfft` in ways that are not compatible with NumPy's API, skip testing the wrapping of the functions and note why they are skipped. Should keep testing relatively straightforward.
|
Thanks for the follow-up comments. I think I have addressed everything raised. Would appreciate another look. |
| "dtype": np.complex_, | ||
| "out_chunk_fn" : _ihfft_out_chunks | ||
| }, | ||
| } |
There was a problem hiding this comment.
The intent behind the data comment is to keep this data outside of functions. That way it can be used by other functions as well.
dtypes = {'fft: ...}
funcs = {'fft': ...
def func(name, ...):
dtype = dtypes[name]
chunk_func = funcs[name]| "`%s` function `%s` doesn't support the NumPy API." % ( | ||
| modname, funcname | ||
| ) | ||
| ) |
There was a problem hiding this comment.
Would the AttributeError check above nt cover this?
There was a problem hiding this comment.
No because as noted in this comment rfft and irfft do exist in SciPy, but they format data in a totally different way than NumPy's rfft and irfft. So we have to massage it into a usable format if we want to test wrapping this function. Not sure it is worth it IMHO.
Determines the unknown `dtype` based on using a dummy array of the same `dtype` as that of the array provided. That way, we are sure it should match the result's `dtype` accurately based on the type we are provided.
Seems the closure doesn't bind the argument from the outer scope function. So hack around this issue by storing it to a variable that is local to the outer function and then copy it over to the inner function. Despite being quite ugly, this does seem to work correctly.
To make sure types are properly handled throughout, try converting the data to single and double precision before proceeding.
Was using `assert_eq`, which is geared for arrays. So fixed this to do a simple equal comparison in an `assert`.
Just to make sure the correct shape is computed for the Dask array, add a test that verifies that the shape of the Dask after the FFT matches that of the actual result.
|
|
||
| wfunc = fft_wrap(func) | ||
| assert wfunc(darrc).dtype == func(nparrc).dtype | ||
| assert wfunc(darrc).shape == func(nparrc).shape |
There was a problem hiding this comment.
The assert_eq function already does this (or if it doesn't, then this fix should go there)
There was a problem hiding this comment.
Ok, well I just noticed that this caused a failure as I'm seeing shape mismatches with *rfft on SciPy. This actually doesn't surprise me as SciPy's functions preserve the original array's shape (up to n). However, NumPy's *rffts don't.
There was a problem hiding this comment.
OK, so I guess this gets back to your original question about if we should support scipy rfft functions, and, if not, how to exclude them. It seems like the current chunk_fn for rfft is specific to numpy. Do we always ask the user to provide a chunk function of their own?
There was a problem hiding this comment.
So I looked at the comparison code and it is checking the shapes, but only after computing the dask arrays. The problem is the shape of the dask is wrong, but the shape of the computed result is correct. Can add a PR to compare these too. Though testing that case may prove tricky.
There was a problem hiding this comment.
PR ( #2101 ) should fix assert_eq to test the shapes before computation, but it looks like it will expose some existing issues. Not sure if I will have time to fix them all though.
There was a problem hiding this comment.
Ah sorry GitHub hid your previous comment. Well one thing to consider (and this might be the right way to fix it) is SciPy and NumPy provide different return types (real or complex). So the chunking function could take the return type as an argument and infer what to do.
Pass around the expected result type of the functions to all of the chunking operations. Use this information to determine the proper chunk sizes particularly for functions like `rfft` and `irfft`, which differ between NumPy and SciPy. However this comes with one caveat, `irfft` will be dispatched according to whether the data is complex (NumPy) or real (SciPy).
| if issubclass(np.dtype(rtype).type, numbers.Real): | ||
| chunks[axis] = (n,) | ||
| else: | ||
| chunks[axis] = (n // 2 + 1,) |
There was a problem hiding this comment.
Is this code tailored exactly to the numpy and scipy conventions or is there something deeper going on here?
If we're just reverse engineering the scipy conventions into these functions then it might be better to just include these as separate functions.
There was a problem hiding this comment.
SciPy's rfft always returns a real array. NumPy's rfft always returns a complex array. These are documented as such in their respective APIs. So this isn't mysterious. We are just leveraging these known differences.
There was a problem hiding this comment.
Is it reasonable for someone to come in with a new fft module and it return a complex dtype but not follow scipy's shape scheme? My question is "are we using dtype to infer which module this is coming from?" If so then we should probably just condition on the module itself rather than back out which module is being used based on what is happening to the dtype.
Taking a step back, is there a way to better handle the shape business here? This all seems somewhat convoluted.
There was a problem hiding this comment.
I guess, but why? If someone did this, it sort of raises the question of did they understand the purpose of SciPy's API at all. The point was to guarantee real values, keep the same shape, and make it easy to invert later. Making all of the values complex makes the array twice as large, but does not add any value as the imaginary parts will all be zero.
That all said, I can't exactly disagree with you. Trying to handle the SciPy *rfft functions is pretty messy and TBH am really not sold on their benefit. They have a few neat tricks, but nothing that really justifies to me why I would want to look at my data in that way instead of an array of complex values.
In short, I'm coming back to the viewpoint that I had when I last looked at this Friday. Namely let's not bother to support the SciPy *rfft functions. If someone wants to try later, we have made their job much easier with work done in this PR. Plus we have already opened the door to people wanting the other SciPy FFT functions or using pyFFTW, which is going to help anyone wanting some extra speed to get it easily with Dask.
There was a problem hiding this comment.
I don't actually care about this specific situation of complex dtypes. My question was intended to reinforce this main point:
My question is "are we using dtype to infer which module this is coming from?" If so then we should probably just condition on the module itself rather than back out which module is being used based on what is happening to the dtype
I'm ok not supporting scipy functions. But we need to actively err here, not just avoid testing them.
Generally the goal of this PR appears to be "allow people to come in with their own fft modules". I guess that the scipy case shows that we can't assume that the "chunk" functions are general.
There was a problem hiding this comment.
Ok, let's move towards erroring out if people use SciPy's *rfft functions then.
FWIW other people think SciPy's *rfft behavior here is weird and are trying to get rid of it.
xref: scipy/scipy#2487
There was a problem hiding this comment.
Have added a ValueError for those specific SciPy functions and added tests that cover it. Also have reverted all of the special dtype handling code.
| if issubclass(a.dtype.type, numbers.Real): | ||
| chunks[axis] = (n,) | ||
| else: | ||
| chunks[axis] = (2 * (n - 1),) |
There was a problem hiding this comment.
Though if there was one that felt funny, this might be it. We are relying on the type to be the correct type for the irfft function we are working with. So if the input array is real, we assume we are dealing with SciPy's irfft. However, if the input array is complex, we are assuming we are dealing with NumPy's irfft. However, NumPy's irfft can take real values in addition to complex ones; whereas, SciPy's irfft can only take real values. I'm not sure if I like it much. It might be ok if documented, but it does allow the user to make a potentially painful mistake.
This reverts commit 4257a2b.
|
Alright, I think this is ready for another look. Please let me know your thoughts. |
| if modname == "scipy.fftpack": | ||
| if "rfft" in funcname: | ||
| with pytest.raises(ValueError): | ||
| wfunc = fft_wrap(func) |
There was a problem hiding this comment.
These two if statements should be merged into one line. Currently you don't test any of the scipy functions except rfft
There was a problem hiding this comment.
Yep, sorry, have merged the ifs.
bcca5af to
45c74a0
Compare
45c74a0 to
b7141eb
Compare
|
Made the last tweak and this is now passing. Please let me know if there is anything else. |
|
Thanks for following through on this @jakirkham . Merged. |
|
Thanks for all the feedback and help getting this together. |
| np_name = fft_func.__name__ | ||
| if fft_func.__doc__ is not None: | ||
| func.__doc__ = (fft_preamble % (np_name, np_name)) + fft_func.__doc__ | ||
| func.__name__ = np_name |
There was a problem hiding this comment.
Missed fixing the docstring for these wrappers to note that these functions could from different locations. Change was made in PR ( #2110 ).
|
|
||
| if modname == "scipy.fftpack" and "rfft" in funcname: | ||
| with pytest.raises(ValueError): | ||
| wfunc = fft_wrap(func) |
There was a problem hiding this comment.
Forgot that this wfunc wasn't doing anything here. So added PR ( #2114 ) to drop the variable assignment since it is unneeded.
|
I just ran across this and I have a question from a user's perspective, not being familiar with the guts.... but it looks like the scipy FFTs wrapped here are going to use numpy ffts? If so I'd like to point a couple things out: I am often taking FFTs of large datasets, and I have observed that the fft implementations out of scipy.fftpack are significantly better at memory handling than the ones out of numpy.fft. I've profiled them to very small timesteps and I can catch the numpy FFT with as much as 8 or 16x the memory of the original array (mid-computation), whereas the scipy FFT only uses something like 2 or 4x. Also, the numpy fft doesn't appear to give back all the memory after it is done. I would very much like to get all my FFTS from one place (I currently have to use the rfftn from numpy, for example), but I don't want to lose wherever the memory advantages of scipy.fftpack are coming from. |
|
I think you are misunderstanding the change, @Jeitan, which is totally understandable as it is in the guts of the library as you say. Before what happened was Dask wrapped up NumPy's 1-D FFT API and let one use that with Dask Arrays. However there was no easy way to sub in an alternative library like SciPy's FFTPACK or pyFFTW to use with Dask. The functions used to do the wrapping were part of the internal or private API. All we did here was clean up the main wrapping function and expose it in the public API. Dask otherwise still provides the same functions as it did before. This allows you to wrap other FFT functions too as long as they conform to the NumPy API. So you could easily wrap SciPy's FFTPACK (with the exception of In short, this change should make it easier to explore FFTs from other libraries (like SciPy's) not harder. If you find that to be otherwise, would be curious to hear more about how and why. * SciPy's FFTPACK functions largely conform to the NumPy API with the notable exceptions of |
|
Ahhhhh, I see @jakirkham, thank you for the explanation! Yes I've been following the rfft discussion, to see how that all unfolds (again as an interested user rather than a dev). I appreciate all the hard work that happens here, looking forward to scipy 1.0! |
Fixes #2092
Provides wrappers for things that implement the standard FFT interface like that of NumPy. Recasts the existing FFT interface with these wrappers. Also adds some tests that exercise this wrapping with NumPy and SciPy.