Skip to content

Add cupyx.scipy.ndimage sum, mean,standard deviation and variance - #3259

Merged
takagi merged 17 commits into
cupy:masterfrom
niteya-shah:scipy.ndimage.sum_mean_variance
Jun 4, 2020
Merged

takagi merged 17 commits into
cupy:masterfrom
niteya-shah:scipy.ndimage.sum_mean_variance

Conversation

@niteya-shah

@niteya-shah niteya-shah commented Apr 3, 2020 •

Copy link
Copy Markdown
Contributor

This PR adds the following routines for cupyx.scipy.ndimage

  • sum
  • mean
  • variance

Currently this method uses Elementwise Kernels,I tried to use Reduction Kernel but couldnt get it to work, if possible can someone recommend a way to use Reduction Kernels.

This PR is still a work in progress.
Todo list

  • Fix variance in accordance to alpha values
  • Performance Testing
  • Add tests
  • Fix Documentation
  • Add more robust type checking

@niteya-shah

Copy link
Copy Markdown
Contributor Author

I did some performance testing and got the following results

size = 10000
numpy
sum                 :    CPU:  211.916 us   +/-101.010 (min:  102.262 / max:  494.926) us
cupy
sum                 :    CPU:  151.134 us   +/-28.169 (min:  128.018 / max:  284.308) us     GPU:  260.936 us   +/-26.983 (min:  238.528 / max:  386.944) us

size = 100000
numpy
sum                 :    CPU:  553.563 us   +/-92.505 (min:  433.164 / max:  958.676) us
cupy
sum                 :    CPU:  203.710 us   +/-84.437 (min:  109.607 / max:  549.043) us     GPU:  822.969 us   +/-82.868 (min:  726.400 / max: 1163.456) us

size = 1000000
numpy
sum                 :    CPU: 6006.947 us   +/-612.652 (min: 5200.629 / max: 7805.347) us
cupy
sum                 :    CPU:  222.765 us   +/-100.760 (min:  105.597 / max:  544.967) us     GPU: 5690.861 us   +/-97.878 (min: 5566.592 / max: 6014.336) us

The large usage of atomicAdd is making this computation extremely slow, I am trying to improve this looking for other reduction methods that could be applied here, as well as moving the label and index lookup to simple hashed map in shared memory( Some guidance here would be helpfull) to reduce the lookup time.

@emcastillo

Copy link
Copy Markdown
Member

Can you post an example of your reduction kernels so we can see why they didn't work?

@niteya-shah

niteya-shah commented Apr 5, 2020 •

Copy link
Copy Markdown
Contributor Author

@emcastillo I couldnt write one because the strategy used in cupy Reduction Kernel relies on interleaved addressing strategies to reduce, but ndimage.sum and its variants, the values are to be selectively summed by a label, which cant summed using the reduction kernel, I dont think we can add values to certain location using our current reduction strategy.( Please correct me If i am wrong anywhere)

I tried to split the difference where in the inital step I create multiple boxes of index shape and fill them according to a split in the labels and then sum them, as a way to reduce the serialization of atomicAdd. A implementation would go like this


def sum(input, labels=None, index=None):

    input_arguments = 'T image, R label, raw X index, int32 size, int32 value'
    _kernel_template = string.Template("""
    for (ptrdiff_t j = 0; j < size; j++) {
      if (label == index[j]) {
        int block = i/value;
        atomicAdd(&ret[j + block * size], image);
        break;
      }
    }
    """)
    output_arguments = 'raw Y ret'
    _kernel_template = _kernel_template.substitute(mean="")
    boxes = 100
    ret = cupy.zeros((index.size * boxes), dtype=input.dtype)
    value = input.size/boxes
    _kernel = cupy.ElementwiseKernel(input_arguments, output_arguments,
                                     _kernel_template, "sumkernel")

    result = _kernel(input, labels, index, index.size, value, ret)
    return result.reshape(boxes, index.size).sum(axis = 0)
 

However even this method was too slow compared to ndimage.sum using numpy.
(The method used in scipy using bincount is about 10 slower than this current method)

Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.py Resolved
@niteya-shah niteya-shah changed the title [WIP] Add cupyx.scipy.ndimage sum, mean and variance [WIP] Add cupyx.scipy.ndimage sum, mean,standard deviation and variance Apr 7, 2020
@niteya-shah

niteya-shah commented Apr 7, 2020 •

Copy link
Copy Markdown
Contributor Author

@emcastillo I added tests and tried to improve the kernel but I think this task is largely serial and I wasn't able to improve it significantly.
I also added the function standard deviation as it was a simple sqrt of variance.

@niteya-shah niteya-shah changed the title [WIP] Add cupyx.scipy.ndimage sum, mean,standard deviation and variance Add cupyx.scipy.ndimage sum, mean,standard deviation and variance Apr 8, 2020
@takagi

takagi commented Apr 10, 2020 •

Copy link
Copy Markdown
Contributor

As for reduction algorithm, the following code does computation equivalent to scipy.ndimage.sum:

import numpy
import cupy
image = cupy.arange(100, dtype=numpy.float32)
labels = cupy.random.choice(3, 100) + 1
index = cupy.array([1, 2, 3])
cupy.where(labels == index[..., None], image, 0).sum(axis=(1,))

Additionally, using cupy.fuse may combine cupy.where and cupy.sum to reduce the number of kernel invocation times to just once.

@grlee77

grlee77 commented Apr 10, 2020

Copy link
Copy Markdown
Member

@takagi
That is a neat, concise implementation. I think it is a reasonable choice when the number of labels to measure is small, but it is not memory efficient when there are a larger number of labels. (the size of some temporary arrays in the input/output of where are image.size * len(index))

I tested the following n-d generalization:

def sum_v2(image, labels, index):
    matched = labels == index.reshape((-1,) + (1,) * image.ndim)
    sum_axes = tuple(range(1, 1 + image.ndim))
    return cupy.where(matched, image, 0).sum(axis=sum_axes, dtype=cupy.intp)

For shape (256, 256, 256), it was indeed faster for 2, 4 or 8 labels, but became substantially slower for larger numbers of labels.

labels sum_v2 This PR
2 14.0 (ms) 27.0 (ms)
4 16.1 (ms) 27.0 (ms)
8 20.2 (ms) 27.0 (ms)
16 28.3 (ms) 19.6 (ms)
32 46.2 (ms) 15.1 (ms)
64 83.5 (ms) 20.5 (ms)

I didn't try it, but I suppose one could run sum_v2 in batches of a few labels at a time rather than on the full set at once to help avoid excessive memory overhead, but I suspect the performance may still be worse for large numbers of labels.

@takagi

takagi commented Apr 11, 2020

Copy link
Copy Markdown
Contributor

@grlee77 Thanks for pointing it out and it makes sense. I tried to implement the same thing with ReductionKernel and cupy.fuse to intend eliminating the use of the temporary array but both made worse performance even with lesser numbers of labels.

BTW, I made a similar performance test as @grlee77 's including scipy.

labels sum_v2 This PR scipy
2 17.2(ms) 39.6(ms) 140.0(ms)
4 18.4(ms) 39.5(ms) 132.9(ms)
8 21.1(ms) 39.5(ms) 132.1(ms)
16 26.3(ms) 28.9(ms) 132.4(ms)
32 36.3(ms) 22.3(ms) 132.1(ms)
64 56.5(ms) 18.4(ms) 131.9(ms)

@niteya-shah

Copy link
Copy Markdown
Contributor Author

Thank you so much @takagi and @grlee77 for your help and insight. I ran the tests myself using sum_v2 and ran out of memory as predicted. I then implemented the batched version as suggested by @grlee77 .

def sum_v3(image, label, index, batch_size = 4):
    out = cupy.empty_like(index, dtype=image.dtype)
    for i in range(0, index.size, batch_size):
        matched = label == index[i:i + batch_size].reshape((-1,) + (1,) * image.ndim)
        sum_axes = tuple(range(1, 1 + image.ndim))
        out[i:i + batch_size] = cupy.where(matched, image, 0).sum(axis=sum_axes)
    return out 

(256, 256, 256), batch_size = 4

label scipy(ms) This PR(ms) sum_v2(ms) sum_v3(ms)
2 103.15 18363.52 33.82 32.58
4 90.99 6955.65 45.58 44.31
8 89.80 3189.20 69.34 88.50
16 89.37 1264.81 176.50
32 90.21 535.65 352.76
64 89.38 172.86 705.50
128 90.91 85.94 1410.12

(For reference my GPU is a 970MX)

Since I cannot compute the values for sum_v2 for larger label sizes, someone else could perhaps try and compare the performance difference that arises due to batching it.

@takagi

takagi commented Apr 14, 2020

Copy link
Copy Markdown
Contributor

atomicAdd might be badly expensive on 970MX? According to the results on @grlee77 's and my environments, the implementation of this PR might be acceptable. And a possible improvement may be that a thread computes multiple elements, for example 16 elements, sequentially on registers to get subtotals for each index, aggregating the subtotals into the output array with atomicAdd. Let me ask for the core members.

@takagi

takagi commented Apr 17, 2020

Copy link
Copy Markdown
Contributor

We talked about this PR and it would be reasonable to use the both algorithms, elementwise one and reduction, switching them by the number of labels empirically given. How do you think?

@niteya-shah

niteya-shah commented Apr 17, 2020 •

Copy link
Copy Markdown
Contributor Author

I think that would be the best solution too, Since my GPU isn't very good with atomicAdd, I started testing my work on Google Colab.
The results for varying sizes and labels are as follows
size : (16, 16, 16)

label_size This PR scipy sum_v2 sum_v3 sum_v4
2 0.05 0.07 0.32 0.35 0.09
4 0.05 0.05 0.24 0.31 0.09
8 0.05 0.05 0.35 0.59 0.09
16 0.06 0.06 0.24 1.11 0.10
32 0.05 0.05 0.34 2.25 0.09
64 0.05 0.05 0.25 4.36 0.09

size : (32, 32, 32)

label_size This PR scipy sum_v2 sum_v3 sum_v4
2 0.12 0.23 0.27 0.32 0.09
4 0.12 0.20 0.27 0.32 0.09
8 0.12 0.22 0.27 0.59 0.09
16 0.11 0.19 0.28 1.12 0.09
32 0.09 0.26 0.31 2.32 0.10
64 0.09 0.20 0.44 4.33 0.11

size : (64, 64, 64)

label_size This PR scipy sum_v2 sum_v3 sum_v4
2 0.67 1.61 0.57 0.63 0.36
4 0.67 1.56 0.65 0.65 0.25
8 0.56 1.34 0.67 1.22 0.20
16 0.49 1.38 0.87 2.44 0.20
32 0.40 1.38 1.22 4.61 0.25
64 0.26 1.40 2.04 9.20 0.33

size : (128, 128, 128)

label_size This PR scipy sum_v2 sum_v3 sum_v4
2 4.99 13.52 3.12 3.17 4.38
4 4.99 11.20 3.47 3.52 3.63
8 3.82 10.71 4.21 6.97 2.96
16 2.99 10.81 5.61 13.84 2.31
32 2.36 10.86 8.53 27.55 1.64
64 1.47 10.81 15.01 54.99 2.06

size : (256, 256, 256)

label_size This PR scipy sum_v2 sum_v3 sum_v4
2 39.50 123.68 23.68 23.57 38.89
4 39.49 116.53 26.50 26.36 38.15
8 28.77 115.36 32.17 52.62 28.21
16 22.00 115.15 43.61 105.14 21.39
32 17.87 115.07 66.90 209.94 17.31
64 11.00 114.70 118.48 419.40 15.63

In my opinium sum_v2 requires a lot of memory, so we should consider sum_v3 for the reduction method, sum_v4 which is a binned method that I proposed earlier doesent seem to outperform the current method.
There is consistency of results for small sizes and hence for smaller dimensions, the sum_v1 method can be used. For larger sizes we can use the sum_v3 method partially.
In my opinion, for label sizes less than 4, we use sum_v3 and for greater than that we use this PR(sum_v1).
Please do correct me if I am wrong anywhere as I have very little experience with heuristic solutions.

@takagi

takagi commented Apr 20, 2020

Copy link
Copy Markdown
Contributor

Thanks for the detail investigation on colab, and switching the algorithms with the label size of 4 sounds good to me! The best candidate of the label size would be 4 or 8, which may vary on environments. I respect your opinion with Tesla P100. Then, would you apply this result to the code of this PR?

Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.py Resolved

@niteya-shah niteya-shah left a comment

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.

I have updated the colab notebook above to reflect the tests for mean. Currently variance is blocked out to due it not working.

Comment thread cupyx/scipy/ndimage/measurements.py Resolved
@niteya-shah

Copy link
Copy Markdown
Contributor Author

@takagi any update on this?

@takagi

takagi commented May 14, 2020

Copy link
Copy Markdown
Contributor

Thanks, let me see the changes shortly!

@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.

Would you check some comments?

Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.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.

Would you check some comments?

Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.py Resolved
Comment thread cupyx/scipy/ndimage/measurements.py Resolved
@takagi takagi removed the st:awaiting-author Awaiting response from author label May 21, 2020
@niteya-shah
niteya-shah requested a review from takagi May 21, 2020 07:22

@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.

Would you check the comments?

@takagi

takagi commented May 22, 2020

Copy link
Copy Markdown
Contributor

Would you parameterize the ndimage operations using @testing.parameterize so that we don't need to repeat similar hand-written tests? You can get the operations by getattr(scp.ndimage, op) where scp is a module name and op a string like 'sum' or 'variance'.

@emcastillo emcastillo added this to the v8.0.0b4 milestone May 29, 2020
@niteya-shah

Copy link
Copy Markdown
Contributor Author

@takagi I have added the float16 tests, with the reduced thresholds.

@takagi

takagi commented Jun 1, 2020

Copy link
Copy Markdown
Contributor

pfnCI, test this please.

@pfn-ci-bot

Copy link
Copy Markdown
Collaborator

Successfully created a job for commit 675aa47:

@chainer-ci

Copy link
Copy Markdown
Member

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

@takagi takagi added the cat:feature New features/APIs label Jun 4, 2020
@takagi

takagi commented Jun 4, 2020

Copy link
Copy Markdown
Contributor

Let me merge this PR to the master. Thanks for your effort! I'll make some cosmetic changes later, which are not essential for your contribution.

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.

6 participants