Skip to content

Add cupy.convolve - #3371

Merged
asi1024 merged 35 commits into
cupy:masterfrom
Dahlia-Chehata:correlate
Jul 1, 2020
Merged

asi1024 merged 35 commits into
cupy:masterfrom
Dahlia-Chehata:correlate

Conversation

@Dahlia-Chehata

Copy link
Copy Markdown
Contributor

No description provided.

@Dahlia-Chehata
Dahlia-Chehata marked this pull request as draft May 27, 2020 03:53
@asi1024 asi1024 self-assigned this May 27, 2020
@Dahlia-Chehata

Copy link
Copy Markdown
Contributor Author

@asi1024 this is a primary version that still needs modifications. Could you please check the overall approach before resuming ?

@leofang

leofang commented May 28, 2020

Copy link
Copy Markdown
Member

It was suggested in the discussion of #3184 that cupy.convolve could be implemented on top of what's done there. Is the plan changed now?

@grlee77

grlee77 commented May 28, 2020 •

Copy link
Copy Markdown
Member

It was suggested in the discussion of #3184 that cupy.convolve could be implemented on top of what's done there. Is the plan changed now?

The biggest issue with that is probably that SciPy's convolve always uses double precision internally and then casts the result to the dtype of the input.

NumPy instead determines appropriate dtypes based on both the input and filter and then performs the convolution using that dtype.

Below are examples in how this leads to different behavior for the two.

case 1: same result, but different dtype

>>> np.convolve(np.arange(8, dtype=np.int16), np.ones(3, dtype=np.uint16), mode='same')
array([1,  3,  6,  9, 12, 15, 18, 13], dtype=int32)

>>>scipy.ndimage.convolve(np.arange(8, dtype=np.int16), np.ones(3, dtype=np.uint16), mode='constant')
array([1,  3,  6,  9, 12, 15, 18, 13], dtype=int16)

case 2: SciPy->floating point values truncated to the input dtype

>>> np.convolve(np.arange(8, dtype=np.int64), np.full((3,), 3.1, dtype=np.float32))
array([ 0.        ,  3.0999999 ,  9.29999971, 18.59999943, 27.89999914,
            37.19999886, 46.49999857, 55.79999828, 40.29999876, 21.69999933])

>>> scipy.ndimage.convolve(np.arange(8, dtype=np.int64), np.full((3,), 3.1, dtype=np.float32))
array([ 3,  9, 18, 27, 37, 46, 55, 61])

case 3: casting negative values to uint16 in SciPy causes unexpected result

>>> np.convolve(np.arange(8, dtype=np.uint16), -np.ones(3, dtype=np.int16))
array([  0,  -1,  -3,  -6,  -9, -12, -15, -18, -13,  -7], dtype=int32)

>>> scipy.ndimage.convolve(np.arange(8, dtype=np.uint16), -np.ones(3, dtype=np.int16))
array([65535, 65533, 65530, 65527, 65524, 65521, 65518, 65516], dtype=uint16)

case 4: float16 not supported in SciPy

>>> np.convolve(np.arange(8, dtype=np.float16), np.ones(3, dtype=np.float16))
array([ 0,  1,  3,  6,  9, 12, 15, 18, 13,  7], dtype=float16)

>>> scipy.ndimage.convolve(np.arange(8, dtype=np.float16), np.ones(3, dtype=np.float16))
RuntimeError: array dtype not supported

@asi1024

asi1024 commented Jun 11, 2020

Copy link
Copy Markdown
Member

@leofang @grlee77 Another implementation seems to be needed for SciPy's convolve.

@asi1024

asi1024 commented Jun 11, 2020

Copy link
Copy Markdown
Member

@Dahlia-Chehata Does it work for non-contiguous input?

@Dahlia-Chehata

Copy link
Copy Markdown
Contributor Author

@Dahlia-Chehata Does it work for non-contiguous input?

Yes, but the input should be converted to contiguous form first

@asi1024

asi1024 commented Jun 14, 2020

Copy link
Copy Markdown
Member

The current implementation does not support complex dtype inputs.

@asi1024

asi1024 commented Jun 14, 2020

Copy link
Copy Markdown
Member

Now I doubt you need to use RawKernel. How about using ReductionKernel?

@Dahlia-Chehata

Dahlia-Chehata commented Jun 14, 2020 •

Copy link
Copy Markdown
Contributor Author

Now I doubt you need to use RawKernel. How about using ReductionKernel?

The thing is that I need to use dynamic parallelism. Each child kernel is invoked with different values of kernel's parameters ( nTPB, nBPG...) . These values depend on the parent's tid. So can this be achieved using ReductionKernel?

@asi1024

asi1024 commented Jun 14, 2020

Copy link
Copy Markdown
Member

In my recognition, dynamic parallelism is often used to speed up recursive operations and does not so good for a simple loop. Actually, the algorithm of your implementation is essentially equivalent to the matrix dot, so the classic matrix multiplication algorithm seems better for the performance.

@asi1024

asi1024 commented Jun 14, 2020

Copy link
Copy Markdown
Member

The current implementation does not pass the following test.

    @testing.numpy_cupy_array_equal()
    def test_large(self, xp):
        a = testing.shaped_arange((4000,), xp, numpy.float64)
        b = testing.shaped_arange((4000,), xp, numpy.float64)
        return xp.correlate(a, b, mode=self.mode)

@Dahlia-Chehata

Dahlia-Chehata commented Jun 14, 2020 •

Copy link
Copy Markdown
Contributor Author

The current implementation does not pass the following test.

    @testing.numpy_cupy_array_equal()
    def test_large(self, xp):
        a = testing.shaped_arange((4000,), xp, numpy.float64)
        b = testing.shaped_arange((4000,), xp, numpy.float64)
        return xp.correlate(a, b, mode=self.mode)

Yes, I know. There are some issues I am still resolving as for example checking if

 if (tid < len){
 }

It is still a draft 😉

@Dahlia-Chehata

Copy link
Copy Markdown
Contributor Author

In my recognition, dynamic parallelism is often used to speed up recursive operations and does not so good for a simple loop. Actually, the algorithm of your implementation is essentially equivalent to the matrix dot, so the classic matrix multiplication algorithm seems better for the performance.

So what is your suggestion ?
Using Reductionkernel for dot product or (maybe it is an existing ufunc.... will look into it) and call it inside a for loop for each of 3 cases: left, middle and right ?

@asi1024

asi1024 commented Jun 14, 2020

Copy link
Copy Markdown
Member

Using ReductionKernel.

@Dahlia-Chehata

Dahlia-Chehata commented Jun 14, 2020 •

Copy link
Copy Markdown
Contributor Author

so the classic matrix multiplication algorithm seems better for the performance.

I know it is early to check the performance (since I am still fixing some bugs and have not pushed the latest fix yet) but I wanted to check whether the performance will be really worse than numpy's

n numpy cupy
100 10.331 149.945
1000 585.134 208.380
10000 59404.040 266.231
100000 5892395.947 280.500

Edit: using 'full' mode

@coderforlife

Copy link
Copy Markdown
Contributor

@Dahlia-Chehata are those numbers times or speeds? Looks like maybe times. What units? Is that n for a cross-correlation?

@Dahlia-Chehata

Copy link
Copy Markdown
Contributor Author

@Dahlia-Chehata are those numbers times or speeds? Looks like maybe times. What units? Is that n for a cross-correlation?

time in us ( didn't change a thing in cupyx.time.repeat)
Yes, n is the size of 1D inputs of correlation

Comment thread cupy/math/misc.py Resolved
@asi1024 asi1024 removed the st:awaiting-author Awaiting response from author label Jun 30, 2020
@asi1024

asi1024 commented Jun 30, 2020

Copy link
Copy Markdown
Member

Jenkins, test this please.

@pfn-ci-bot

Copy link
Copy Markdown
Collaborator

Successfully created a job for commit 845e786:

@chainer-ci

Copy link
Copy Markdown
Member

Jenkins CI test (for commit 845e786, target branch master) failed with status FAILURE.

@asi1024

asi1024 commented Jun 30, 2020

Copy link
Copy Markdown
Member

Could you remove this line?

{'func': fallback_mode.numpy.convolve, 'shape': (5,)}

The test TestNotificationModes seems to assume that cupy.convolve is not implemented.

@asi1024

asi1024 commented Jul 1, 2020

Copy link
Copy Markdown
Member

Jenkins, test this please.

@pfn-ci-bot

Copy link
Copy Markdown
Collaborator

Successfully created a job for commit 8623128:

@chainer-ci

Copy link
Copy Markdown
Member

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

@ke-zhang-rd

ke-zhang-rd commented Jul 1, 2020 •

Copy link
Copy Markdown

This looks nice but why only addresses 1d not Nd?

I notice numpy.convolve focus on 1d but I believe that is because of numpy and scipy negotiation which let them focus separately implement convolve and scipy implements Nd convolve. While cupy is oligopoly in this domain, I feel cupy need to cover Nd.

@asi1024

asi1024 commented Jul 1, 2020

Copy link
Copy Markdown
Member

@ke-zhang-rd CuPy aims to support NumPy compatible interface, so we won't support Nd array inputs in cupy.convolve. We will support it in cupyx.scipy.signal.convolve in the future.

@asi1024

asi1024 commented Jul 1, 2020

Copy link
Copy Markdown
Member

Jenkins, test this please.

@pfn-ci-bot

Copy link
Copy Markdown
Collaborator

Successfully created a job for commit b4acd1d:

@chainer-ci

Copy link
Copy Markdown
Member

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

@asi1024

asi1024 commented Jul 1, 2020

Copy link
Copy Markdown
Member

LGTM.

@asi1024
asi1024 merged commit 11061ca into cupy:master Jul 1, 2020
@Dahlia-Chehata
Dahlia-Chehata deleted the correlate branch July 1, 2020 09:41
@ke-zhang-rd

Copy link
Copy Markdown

@ke-zhang-rd CuPy aims to support NumPy compatible interface, so we won't support Nd array inputs in cupy.convolve. We will support it in cupyx.scipy.signal.convolve in the future.

@asi1024 Ok, is there anyone implementing that? If not, I could help.

@coderforlife

Copy link
Copy Markdown
Contributor

@ke-zhang-rd See #3526 which shows that this particular implementation of convolve is extremely slow, especially for smaller inputs. It may be a better approach to utilize the much faster cupyx.scipy.ndimage.convolve function (or at least it's approach) to implement cupyx.scipy.signal.convolve. In fact, if you are willing to copy the input array when mode='full' (by using the cupy.pad function), there is already quick-and-dirty implementations of cupyx.scipy.signal.convolve using cupyx.scipy.ndimage.convolve.

I do have plans on making cupyx.scipy.ndimage.convolve usable for mode='full' directly and thus you can use it for those other implementations.

@asi1024

asi1024 commented Jul 6, 2020 •

Copy link
Copy Markdown
Member

@coderforlife CuPy aims to handle large inputs, so if you want to talk about performance, you should compare on large inputs. (It is better to have good performance even with small inputs of course! 😄)
Please note that it is hard to say which one is better depending on the shape of inputs.

script:

import numpy
import scipy.ndimage

import cupy
import cupyx
import cupyx.scipy.ndimage

a_shapes = [10, 2000000]
v_shapes = [2000000, 10]

for a_shape, v_shape in zip(a_shapes, v_shapes):
    a = cupy.arange(a_shape, dtype=numpy.int32)
    v = cupy.arange(v_shape, dtype=numpy.int32)

    perf = cupyx.time.repeat(
        cupy.convolve, (a, v, 'same'),
        max_duration=1)
    print(perf)
    perf = cupyx.time.repeat(
        cupyx.scipy.ndimage.convolve1d, (a, v), {'mode': 'constant'},
        max_duration=1)
    print(perf)

Results:

convolve            :    CPU:   92.901 us   +/-40.204 (min:   86.524 / max: 1544.412) us     GPU-0:  731.759 us   +/-46.062 (min:  711.104 / max: 2168.384) us
convolve1d          :    CPU:  133.567 us   +/-115.531 (min:   58.519 / max:  333.251) us     GPU-0:266243.317 us   +/-120.219 (min:266173.096 / max:266451.538) us
convolve            :    CPU:   89.753 us   +/-11.573 (min:   86.483 / max:  509.197) us     GPU-0:  715.934 us   +/-11.555 (min:  712.544 / max: 1135.040) us
convolve1d          :    CPU:   49.686 us   +/- 3.497 (min:   47.859 / max:  328.524) us     GPU-0:   87.957 us   +/- 3.338 (min:   84.608 / max:  363.008) us

cupy.convolve is x8 slower in some case, cupyx.scipy.ndimage.convolve1d is x360 slower in some case...

@coderforlife

Copy link
Copy Markdown
Contributor

@asi1024 The scipy.ndimage functions intentionally do not swap a or v to force a being larger like cupy.convolve does. This is required for scipy compatibility. However, if cupy.convolve was made as a wrapper of them, then this simple statement could be added to the wrapper: if a.size < v.size: a,v = v,a. This line already exists in cupy.convolve in fact. Thus, the 360x slower case would not be seen ever.

See the basic wrapper at #3414 (comment) and test against that. That wrapper does support 'full' and 'valid' modes as well, but 'full' is done in such a way it will incur a penalty - I am currently making a version of the convolve function based on the scipy.ndimage functions that will natively support 'full' and 'valid' and thus incur no penalties for those modes. It currently works for the 1D cupy.convolve function but needs some fixes to work for the nd cupyx.scipy.signal.convovle functions.

@coderforlife

Copy link
Copy Markdown
Contributor

@asi1024 And yes, I regular test on large arrays. A basic 4MP image is twice as large as the size you used.

The only times when cupy.convolve is good competition is when a.size is very close to v.size and they are fairly large.

@leofang

leofang commented Jul 6, 2020 •

Copy link
Copy Markdown
Member

I don't speak for @asi1024, but the objection which I (and @ke-zhang-rd who is working on a FFT-based cupyx.scipy.signal.convovle) would have is to your earlier statement

See #3526 which shows that this particular implementation of convolve is extremely slow, especially for smaller inputs.

Calling it "extremely slow" is very unfair to @Dahlia-Chehata's contribution. The point is CuPy focuses the performance for large inputs, and there requires some different, specialized considerations and approaches for small inputs. Often times, for the input sizes you tested in #3526 I'd just recommend to use SciPy directly, as GPUs won't win CPUs overwhelmingly and SciPy has been well-optimized.

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.

9 participants