Skip to content

Add NumPy v1.17 new random API with Generator - #4177

Merged
asi1024 merged 47 commits into
cupy:masterfrom
emcastillo:bitgenerator
Jan 6, 2021
Merged

asi1024 merged 47 commits into
cupy:masterfrom
emcastillo:bitgenerator

Conversation

@emcastillo

@emcastillo emcastillo commented Oct 26, 2020 •

Copy link
Copy Markdown
Member

This is still on-going

Due to some issues when generating the distributions in #4163, the added bit generators will use only the curand device API

I have spent a great deal of time trying to figure out how to correctly templatize the code, some ideas will be greatly appreciated. The idea is that we want multiple curand generators (or custom ones) to be supported in the kernels that implement the distributions. The generators are usually specified in the BitGenerator in python so we need to get that type info down to the Cython level.

TODO

  • HIP
  • Add minimum set of distributions (normal, uniform, exponential)
  • Support all device curand generators
  • Tests

@emcastillo

emcastillo commented Oct 26, 2020 •

Copy link
Copy Markdown
Member Author

I tried to design some templatized mechanism for the kernels to allow any type of generator obbeying the API,
However there are several limitations that made this approach not feasible at the first try.

The idea was that the BitGenerators in python have a method that returns a wrapped instance of their corresponding C generator object.
But at the time of calling the templatized module, the wrapped instance is always a PyObj because we can't determine the type at compile time since this is doing several kinds of polimorphism. So in the end the correct template can't be invoked unless the object is explicitly casted to the correct type, which is something I wanted to avoid.

Comment thread cupy_setup_build.py Resolved
@emcastillo

Copy link
Copy Markdown
Member Author

Added an integers naive implementation that takes 25 us to generate 10.000 elements compared to the 500 us of the current randint

Comment thread cupy/random/cupy_distributions.cu Resolved
Comment thread cupy/random/cupy_distributions.cu Resolved
Comment thread cupy/random/cupy_distributions.cu Outdated
};

template<typename F, typename T, typename R, typename... Args>
__global__ void execute_dist(intptr_t param, void* out, ssize_t size, Args... args) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

since all the distributions use the same kernel, this avoids the need to write redundant kernels, however If there was an easy way to templatize the functors too, it would be awesome.

@emcastillo

Copy link
Copy Markdown
Member Author

Btw, randint with this is super fast, around 26 us to generate 10.000 random integers compared to 500 us of current cupy implementation

Comment thread cupy/random/cupy_distributions.cu Outdated
template <typename F, typename R>
struct kernel_launcher {
template<typename T, typename... Args>
void operator()(int bpg, int tpb, cudaStream_t stream, Args&&... args) {

@emcastillo emcastillo Oct 29, 2020 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

we can't have kernels as class methods, so we have to resort to dirty tricks like this ...

Comment thread cupy/random/cupy_distributions.cu Outdated
template <typename F, typename... Ts>
void generator_dispatcher(int generator_id, F f, int bpg, int tpb, cudaStream_t stream, Ts&&... args) {
switch(generator_id) {
case CURAND_XOR_WOW: return f.template operator()<curand_xor_state>(bpg, tpb, stream, std::forward<Ts>(args)...);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Data comes from python, so we lose it in the inheritance hierarchy of BitGenerator :( and this makes imposible to directly instatiate a template. We have to use an enum like this.

Comment thread cupy/random/cupy_distributions.cu Outdated
}


__device__ uint32_t rk_interval_32(rk_state* state, int mx, int mask) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

fix int types here

@leofang leofang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks good! Just did a quick pass and left some 1st round comments.

Comment thread cupy/random/_bit_generator.pyx Outdated
Comment on lines +180 to +183
chunks = (out.size + bsize - 1) // bsize
for i in range(chunks):
y_ptr = <intptr_t>out[i*bsize:].data.ptr
func(generator, state, y_ptr, bsize, strm, *args)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What happens for the last chunk that might be smaller than bsize?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

good catch!

Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Outdated
Comment on lines +26 to +30
void init_curand_generator(int generator, intptr_t state_ptr, uint64_t seed, ssize_t size, intptr_t stream);
void interval_32(int generator, intptr_t state, intptr_t out, ssize_t size, intptr_t stream, int mx, int mask);
void interval_64(int generator, intptr_t state, intptr_t out, ssize_t size, intptr_t stream, uint64_t mx, uint64_t mask);
void beta(int generator, intptr_t state, intptr_t out, ssize_t size, intptr_t stream, double a, double b);
void exponential(int generator, intptr_t state, intptr_t out, ssize_t size, intptr_t stream);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think you don't need the tailing semicolons.

Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
generator = CURAND_XOR_WOW # Use The Enum

def _type_size(self):
return sizeof(curandState)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I am a bit confused: what's the difference between curandState and curandState_t?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

no one knows, they are used interchangeably in the documentation, but we should stick to only one, will fix

Comment thread cupy/random/_bit_generator.pyx Resolved
@leofang

leofang commented Nov 2, 2020

Copy link
Copy Markdown
Member

87e959a fixed the C++ error, but we still have errors due to using variadic arguments (#4177 (comment)).

@emcastillo

Copy link
Copy Markdown
Member Author

Would like some feedback on the new design :)

@emcastillo
emcastillo force-pushed the bitgenerator branch 3 times, most recently from d9a0163 to aa149e1 Compare November 18, 2020 09:59
@emcastillo
emcastillo marked this pull request as ready for review November 18, 2020 09:59
left=self.left, mode=self.mode, right=self.right, size=(3, 2))


"""

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

will remove this

@emcastillo emcastillo changed the title [WIP] Add NumPy v1.17 new random API with Generator Add NumPy v1.17 new random API with Generator Nov 18, 2020

@leofang leofang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Very quick first-pass scan, mostly on style. Will take a deeper look later.

I don't fully understand the design decision, likely because I'm not familiar with either NumPy's or cuRAND's API, will look into them to understand things better.

I noticed some classes in .pyx are plain Python classes. Given the simplicity of data management here, I am not too worried about not turning them into cdef classes. But it'd be good to have a benchmark done. Is it possible to compare random number generation throughput before and after this PR?

Based on offline discussion with @emcastillo we think it's straightforward to add HIP support. Given the massive amount of changes in this PR I suggest we defer it (I could try to handle it in a separate PR).

Comment thread cupy/random/_bit_generator.pyx Resolved
# Size is the number of threads that will be initialized
def __init__(self, seed=None, *, size=10000*256):
super().__init__(seed)
# Raw kernel has problems with integers with the 64th bit set

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What does this mean?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

When passing a 64-bit unsigned integer as a parameter to a raw kernel, it is cast somewhere in the code to a signed one using numpy.int64, if that integer has its 64-th bit set, then an Out of range error is raised 😔

Comment on lines +60 to +67
def _check_device(self):
if cupy.cuda.Device().id != self._current_device:
raise RuntimeError(
'This Generator state is allocated in a different device')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

So what happens when the users switch the device?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This should error, users shouldn't be able to use a generator with its state allocated in one device, in another device.

state. One may also pass in a `SeedSequence` instance.
"""
def __init__(self, seed=None):
self.lock = threading.Lock()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What's the purpose of self.lock? I don't find it used anywhere.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yeah, it is actually documented in the numpy API, but I believe we don't need it, so I can get rid of it.

@asi1024 asi1024 Nov 24, 2020 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe self.lock should be used in random_raw of subclasses.
The kernel invocations are atomic themselves, so we can run _launch_dist in parallel.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The user's custom generator class may require self.lock, so let's leave this interface!

Comment thread cupy/random/_distributions_module.py Resolved
Comment thread cupy/random/_distributions_module.py Resolved
Comment thread cupy/random/_distributions_module.py Resolved
Comment thread cupy/random/_distributions_module.py Resolved
Comment thread cupy/random/_distributions_module.py Resolved
Comment thread cupy/random/_generator.pyx Resolved
Comment thread cupy/random/_distributions_module.py Resolved
Comment thread cupy/random/cupy_distributions.cu Resolved
@asi1024

asi1024 commented Nov 24, 2020

Copy link
Copy Markdown
Member

Jenkins, test this please.

@chainer-ci

Copy link
Copy Markdown
Member

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

@emcastillo

Copy link
Copy Markdown
Member Author

Jenkins, test this please

@chainer-ci

Copy link
Copy Markdown
Member

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

@emcastillo

emcastillo commented Dec 22, 2020 •

Copy link
Copy Markdown
Member Author

the lack of redistributable curand headers motivated us to restore the old module-based approach.
@asi1024 @leofang PTAL!
If this can be landed tomorrow, it will be great for the release

Comment thread cupy/random/__init__.py Resolved
Comment thread cupy/random/__init__.py Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_bit_generator.pyx Resolved
Comment thread cupy/random/_generator.pyx Resolved
Comment thread cupy/random/_generator.pyx Resolved
Comment thread cupy/random/_generator.pyx Resolved
Comment thread cupy/random/_generator.pyx Resolved

@leofang leofang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could you add a comment to explain why this is disabled for HIP? Perhaps you can add the link to ROCm/hip#2186.

Comment thread cupy/random/_generator.pyx Resolved
@emcastillo

Copy link
Copy Markdown
Member Author

PTAL!

@asi1024

asi1024 commented Jan 5, 2021

Copy link
Copy Markdown
Member

Jenkins, test this please.

@chainer-ci

Copy link
Copy Markdown
Member

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

@emcastillo

Copy link
Copy Markdown
Member Author

Jenkins, test this please

@cupy cupy deleted a comment from chainer-ci Jan 6, 2021
@cupy cupy deleted a comment from chainer-ci Jan 6, 2021
@cupy cupy deleted a comment from chainer-ci Jan 6, 2021
@chainer-ci

ghost commented Jan 6, 2021

Copy link
Copy Markdown
Member

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

@asi1024

ghost commented Jan 6, 2021

Copy link
Copy Markdown
Member

LGTM!

@asi1024
asi1024 merged commit 75eb595 into cupy:master Jan 6, 2021
@asi1024 asi1024 added this to the v9.0.0b2 milestone Jan 6, 2021
@leofang

ghost commented Jan 6, 2021

Copy link
Copy Markdown
Member

Awesome work @emcastillo!!!

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants