Skip to content

Adding scipy.signal functions that are simple wrappers of ndimage functions - #3645

Merged
takagi merged 9 commits into
cupy:masterfrom
coderforlife:signaltools
Aug 7, 2020
Merged

takagi merged 9 commits into
cupy:masterfrom
coderforlife:signaltools

Conversation

@coderforlife

Copy link
Copy Markdown
Contributor

I have implemented most of scipy.signal.signaltools. This is the first batch that should be the most straightforward since it is just utilizing the ndimage functions which includes:

  • wiener
  • order_filter
  • med_filt
  • med_filt2d
  • sepfir2d (which is actually in bsplines.py)

Next batch will be some of the utility functions and functions like hilbert. After that will be convolve and friends (but those are dependent on #3614). After that, there will be lfilter and sosfilt and friends. By then I may have the splines completed as well.

Currently there are no formal tests for these but those are coming shortly.

@leofang

leofang commented Jul 23, 2020

Copy link
Copy Markdown
Member

Tagging signal processing experts @mnicely @awthomp

@awthomp

awthomp commented Jul 23, 2020

Copy link
Copy Markdown

Thanks for the ping, @leofang!

@coderforlife - please check out cuSignal. We already have support for many of these functions (lfilter on GPU is close to impossible, though!) and would love to have you contribute.

https://github.com/rapidsai/cusignal

@coderforlife

Copy link
Copy Markdown
Contributor Author

I know those are there, but I thought this scipy was supposed to be near duplication of scipy and the what would be (or is) in a scikit would be in cuSignal, cuImage, or similar. Missing them here is a bit confusing.

Also, the functions in this commit are essentially freebies since they just call the ndimage functions after doing a small amount with the arguments (like checking).

I have been struggling with lfilter as well... best parallelization so far is with each signal/channel. But I have a few ideas, although they may not pan out.

@awthomp

awthomp commented Jul 23, 2020

Copy link
Copy Markdown

I know those are there, but I thought this scipy was supposed to be near duplication of scipy and the what would be (or is) in a scikit would be in cuSignal, cuImage, or similar. Missing them here is a bit confusing.

Also, the functions in this commit are essentially freebies since they just call the ndimage functions after doing a small amount with the arguments (like checking).

I have been struggling with lfilter as well... best parallelization so far is with each signal/channel. But I have a few ideas, although they may not pan out.

I'll default to whatever the core CuPy devs want. cuSignal heavily depends on this wonderful library, so even wrapping functions core to CuPy within cuSignal is totally fine with me.

As for the heavy-weight signal processing functions, like lfilter and sosfilt, in particular, I think it does make more sense for us to include these in cuSignal, but I'll admit I'm biased.

Here's our work with lfilter: rapidsai/cusignal#78. We found there's a data dependency in the DF-II implementation, and our way around this was to have a single thread CUDA kernel and hope to get E2E acceleration. This didn't work out, and we deprecated our work here: rapidsai/cusignal#93

Here's our sosfilt implementation: rapidsai/cusignal#99

@grlee77

grlee77 commented Jul 23, 2020 •

Copy link
Copy Markdown
Member

Here's our work with lfilter: rapidsai/cusignal#78. We found there's a data dependency in the DF-II implementation, and our way around this was to have a single thread CUDA kernel and hope to get E2E acceleration. This didn't work out, and we deprecated our work here: rapidsai/cusignal#93

I implemented the specific IIR filters for the spline_prefilter and spline_prefilter1d functions from scipy.ndimage.interpolation. It will be slow in 1D, but I found that for ndim >= 2, it was possible to run 1 line of data per GPU thread and get reasonable acceleration. Here is a quick benchmark example.

import cupy as cp
import numpy as np
import scipy.ndimage as ndi
from cupyimg.scipy.ndimage import spline_filter1d

d = cp.cuda.Device()
a = np.random.randn(4096,  4096).astype(np.float32)
a_gpu = cp.asarray(a)

%timeit ndi.spline_filter1d(a)
%timeit spline_filter1d(a_gpu); d.synchronize()

Here the CPU time was: 186 ms ± 716 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
and the GPU time was: 6.9 ms ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

If I instead ravel the same arrays so that they are 1D, the CPU time becomes 237 ms and GPU becomes MUCH longer at 3750 ms as it can no longer split up the work line-by-line on the GPU.

For reference: The spline kernel code is here and the configuration of RawKernel and block/grid is here. I think the kernel is basically the same type of code as lfilter, just with hard-coded a, b corresponding to various spline orders and some specific boundary handling cases that aren't present in lfilter.

@coderforlife

Copy link
Copy Markdown
Contributor Author

@grlee77 @awthomp There are ways to make even IIR filters across single signals parallel. I am trying them out now to see if there is an improvement in speed (they require more computations, but in turn allow parallelization).

@coderforlife

Copy link
Copy Markdown
Contributor Author

@grlee77 My currently version only parallelizes across the signals like you suggest.

@awthomp I looked through your code and I was starting to approach something similar with a few differences. It seems as though the x*b can be done completely parallel for each sample (assuming a_len is less than x_len). That's over half of the work for each sample done in parallel. Those results are stored in out. Then scan through and subtract off the a*y. You are doing more work overall, but it seems as though it might make up for it. I am going to try a version like that right now.

@coderforlife

coderforlife commented Jul 24, 2020 •

Copy link
Copy Markdown
Contributor Author

@awthomp I have had some success with this! By having the x*b portion completely parallelized and then doing y*a in parallel over the signals/channels I see a 50% to 85% speed improvement over my old method that only parallelized over signals.

I have now created 3 versions:

  1. My original version which operated in parallel across signals but not within the samples for a single signal, may not have been well-optimized in other ways.
  2. My second version where I made an ElementwiseKernel to do the x*b step completely in parallel and then a RawKernel to do the y*a in parallel across signals. I never completed this version so it doesn't support zi/zf. It also has a bug right now and doesn't generate the correct output.
  3. While making v2 I realized that the ElementwiseKernel was really just doing a convolution and I should reuse my already-made convolve function! The third version uses convolve for the x*b step and then the same RawKernel from v2 (with some minor modifications to support zi/zf).

I tested with 2^20 elements and started at having an equal number of signals and samples (both 1024) and then reduced signals while increasing the samples until getting to only 1 signal with 2^20 samples. The b and a vectors have 7 elements each. Here is the timing data (in ms, from a Titan V GPU) with percent of time of v1.

  v1 v2   v3  
1024x1024 1.68 0.986 59% 0.699 42%
512x2048 3.13 1.79 57% 1.2 38%
256x4096 6.11 3.4 56% 2.28 37%
128x8192 12 6.62 55% 4.24 35%
64x16384 21.1 6.83 32% 5.72 27%
32x32768 40.3 9.73 24% 10.4 26%
16x65536 72.6 13.8 19% 16.4 23%
8x131072 142 23.3 16% 31.8 22%
4x262144 276 43.9 16% 61.4 22%
2x524288 542 81.9 15% 101 19%
1x1048576 352 156 44% 156 44%

Overall, v2 and v3 are between 15% and 44% of the original's time. There is a strange behavior in the v2 is faster near the bottom and v3 is faster near the top. I am really curious why this is (it also has a bug so maybe those timings aren't good anyways). Also, everyone sucks at 1x however v1 actually is faster at 1x than 2x. For reference, all of these take 6.5-6.65 ms with scipy.signal.lfilter, so only from 64 signals and above is cupy beating scipy.

BTW, all of these version support ND data in the same way the scipy does (one axis is considered the samples, all other axes are signals).

Finally, I tried against your implementation (only the last row up there since yours only supports 1D), and yours takes 738 ms vs 352 (v1) or 156 (v2 and v3). I have no idea why yours is so much slower. But, for me, I haven't tried adding __restrict__ to my pointers yet... maybe I will get some improvement!

@coderforlife

Copy link
Copy Markdown
Contributor Author

@awthomp Another benefit of the new approach is that b and a can be different lengths without needing to be 0-padded since each is used completely separately.

@awthomp

awthomp commented Jul 24, 2020

Copy link
Copy Markdown

@coderforlife so happy to see you making progress. I’ll be in and out over the next two weeks for vacation. These optimizations were all due to the great work from @mnicely, and I’m sure he’ll be able to help.

@coderforlife

Copy link
Copy Markdown
Contributor Author

I think we should move this discussion out of this PR since it has nothing to do with these first few filters.

For now, just need approval of current 5 filters which all just utilize the ndimage.filters functions to do nearly all of the work.

@coderforlife

Copy link
Copy Markdown
Contributor Author

Seems as though the signal processing experts are okay with this. It really is just mapping some signal functions to their equivalents in ndimage (wiener is a bit more complex, but only slightly).

Comment thread cupyx/__init__.py Resolved
Comment thread cupyx/scipy/signal/bsplines.py Resolved
Comment thread cupyx/scipy/signal/bsplines.py Resolved

@takagi takagi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very sorry for the late review. Would you check the comments?

Comment on lines +9 to +13

try:
import scipy.signal # NOQA
except ImportError:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you remove these lines?

Suggested change
try:
import scipy.signal # NOQA
except ImportError:
pass

@coderforlife coderforlife Aug 2, 2020 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing these will cause all new tests to fail because they won't be able to use cupyx.scipy.signal or scipy.signal (used as scp.signal later with scp either cupyx.scipy or scipy).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. @testing.numpy_cupy_allclose imports just scipy and cupyx.scipy packages only, and scipy.signal and cupyx.scipy.signal can't be seen.

Comment on lines +4 to +10

import cupyx.scipy.signal # NOQA

try:
import scipy.signal # NOQA
except ImportError:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you remove these lines?

Suggested change
import cupyx.scipy.signal # NOQA
try:
import scipy.signal # NOQA
except ImportError:
pass

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing these will cause all tests to fail because they won't be able to use cupyx.scipy.signal or scipy.signal (used as scp.signal later with scp either cupyx.scipy or scipy).

Comment thread cupyx/scipy/signal/signaltools.py Resolved
Comment thread cupyx/scipy/signal/signaltools.py Resolved
@takagi takagi added the cat:feature New features/APIs label Aug 1, 2020
@takagi takagi added this to the v8.0.0rc1 milestone Aug 1, 2020
@coderforlife

Copy link
Copy Markdown
Contributor Author

No problem, I understand it must be busy with the recent releases. I fixed all of the issues except the ones where if I remove those lines everything fails. Also, I am going to try right now to add support for complex dtypes (support actually already exists, it just isn't directly accessible).

@coderforlife

Copy link
Copy Markdown
Contributor Author

So I was able to fairly easily add complex support to both signal.bsplines.sepfir2 and signal.signaltools.wiener however it required duplicating code from ndimage.filters and ndimage._filters_core. I am unsure if it wouldn't be better to simply add an extra bool argument to several ndimage.filters functions that simply allows turning off the requirement of intermediate results must be float64 (that is to reproduce scipy's behavior and prevents complex numbers from working). I think that discussion can happen elsewhere though and for now we can just avoid complex in this PR.

@takagi

takagi commented Aug 5, 2020

Copy link
Copy Markdown
Contributor

Thanks for updating the changes, and it is fine to leave complex unsupported here.

@takagi

takagi commented Aug 5, 2020

Copy link
Copy Markdown
Contributor

pfnCI, test this please.

@pfn-ci-bot

Copy link
Copy Markdown
Collaborator

Successfully created a job for commit 690eb26:

@chainer-ci

Copy link
Copy Markdown
Member

Jenkins CI test (for commit 690eb26, target branch master) succeeded!

@takagi

takagi commented Aug 7, 2020

Copy link
Copy Markdown
Contributor

LGTM!

@takagi
takagi merged commit e157ca2 into cupy:master Aug 7, 2020
@asi1024 asi1024 mentioned this pull request Aug 7, 2020
@leofang

leofang commented Aug 10, 2020

Copy link
Copy Markdown
Member

@coderforlife We're seeing irrelevant PRs (#3730, #3735) failing at tests/cupyx_tests/scipy_tests/signal_tests/test_bsplines.py, but only on one of the CIs. Do you happen to know if it's due to the different SciPy version that it used?

@coderforlife

Copy link
Copy Markdown
Contributor Author

It turns out that there is a bug in scipy. Way down in the source code for sepfir2d I found this comment: /* h must be odd length */. However, scipy never enforces this or has this in the public documentation. You will notice that all of the failing ones have even hcol and/or hrow.

For the moment I have submitted the issue at scipy: scipy/scipy#12691. I think in the mean time we should add a check in cupyx.scipy.signal.bsplines for even-length hrow and hcol that raises an exception and remove even-length tests.

@leofang

leofang commented Aug 10, 2020

Copy link
Copy Markdown
Member

Great, thanks for pinpointing the issue so quickly, @coderforlife! I am wondering if the errors could happen randomly? It's not always reproducible on the failing CI (for example, this PR went in just fine, and a few other PRs too).

@coderforlife

Copy link
Copy Markdown
Contributor Author

Well scipy's sepfir2d is reading out-of-bounds memory when the length of hrow or hcol is even so yes, it has random effects since whatever the memory contents is that it ends up reading.

@leofang

leofang commented Aug 10, 2020

Copy link
Copy Markdown
Member

Yeah can't reproduced it locally...

@coderforlife

Copy link
Copy Markdown
Contributor Author

Different memory allocator or something.

@coderforlife

Copy link
Copy Markdown
Contributor Author

See #3750.

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

Labels

cat:feature New features/APIs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants