# More on CUDA Random Numbers.

**URL:** <https://forums.developer.nvidia.com/t/more-on-cuda-random-numbers/9627>\
**Category:** CUDA Programming and Performance\
**Created:** [May 21, 2009, 9:31pm UTC](https://forums.developer.nvidia.com/t/more-on-cuda-random-numbers/9627 "2009-05-21T21:31:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![zaz](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@zaz](https://forums.developer.nvidia.com/u/zaz)\
**Post date:** [May 21, 2009, 9:31pm UTC](https://forums.developer.nvidia.com/t/more-on-cuda-random-numbers/9627/1 "2009-05-21T21:31:19Z")

</div>

I want to use a random number generator (RNG) without (initially) having to become too expert about it. Mersenne Twisters seem to be well established though there are some subtleties with parallel implementations like CUDA. MT19937 seems to be a well used Mersenne Twister, and Brian Mills has posted a CUDA version to this forum.  
See

[url=“[http://forums.nvidia.com/index.php?showtopic=31159&st=20&p=217039&#entry217039](http://forums.nvidia.com/index.php?showtopic=31159&st=20&p=217039&#entry217039)”][http://forums.nvidia.com/index.php?showtop...mp;#entry217039[/url]](http://forums.nvidia.com/index.php?showtop...mp;#entry217039%5B/url%5D)

I have not seen any “user 's manual” for Brians code so I have attempted an annotated example below. It is meant to generate independent uniformly-distributed random integers on the interval [0, 2^32 - 1] for each thread in a CUDA-grid. The threads are grouped in CUDA-blocks of course, but each distinct thread in the entire grid hopefully receives independent randoms.

The code is untested, but it compiles and runs on a GTX285. See comments within the example code for more details.

My example is not meant to be fast or used for speed tests, but is meant to be correct. It is based on my reading of Brian’s test code. I have used strange numbers for “numbers of blocks” and “numbers of threads (per block)”. I am mostly interested in whether the code is correct, and will generated good quality random numbers.

Please comment on:

1. The correctness of my use of Brian’s routines.
2. The correctness and efficiency of Brian’s implementation within the CUDA environment.
3. Whether this form of parallelism is adequate or if some form of “spawnTwisters.c”, as used in the CUDA SDK (MersenneTwister) is needed.

Thanks!

-------- CUDA Code follows --------------------  
/\*  
Uniform random unsigned ints on interval [0, 2^32].

This file contains an annotated example of the use  
of Eric Mills’ mt19937 Mersenne Twister for CUDA,  
which generates uniform random 32-bit unsigned ints  
for CUDA-threads executed in CUDA-blocks.

Eric’s implementation can be copied from:

[url=“[http://forums.nvidia.com/index.php?showtopic=31159&st=20&p=217039&#entry217039](http://forums.nvidia.com/index.php?showtopic=31159&st=20&p=217039&#entry217039)”][http://forums.nvidia.com/index.php?showtop...mp;#entry217039[/url]](http://forums.nvidia.com/index.php?showtop...mp;#entry217039%5B/url%5D)

Four example kernels are exhibited:  
shared\_mem\_227\_kern — uses shared memory and up to 227 threads  
shared\_mem\_unlimited\_kern — uses shared memory and unlimited number of thread  
global\_mem\_227\_kern — uses global memory and up to 227 threads  
global\_mem\_unlimited\_kern — uses global memory and unlimited number of thread

To modify this module for different applications,  
choose one of the above kernels, and  
search for “your kernel-code here”.

The code works by creating an array of randoms using  
a (non-parallelized) Mersenne Twister named genrand\_int32().  
The array name is d\_bseeds and it is created by calling  
create\_block\_seed\_array(). Each element of d\_bseeds  
corresponds to a CUDA-block, and is used when the block  
starts running to generate an individual seed for each  
CUDA-thread within the block by calling either  
mt19937si() or mt19937gi().

This scheme does have the possibilty of collisions  
between the numbers generated in distinct CUDA-threads,  
but my understanding is that collisions are unlikely  
because of the large state space used in  
Mersenne Twisters. I believe the Mersenne Twister  
example currently (May-2009) in the SKD uses  
spawnTwister to generate distinct Mersenne Twisters  
with even less chance of collision.  
This paragraph is based on my own speculations  
and may be incorrect. (If you know better, please  
let me know!)

For simplicity I have just included two of Eric’s  
files, mt19937\_ref.cu and mt19937\_gold.cpp  
int this code using #include. See below.

Compile using:  
/usr/local/cuda/bin/nvcc   
-I -I. -I/usr/local/cuda/include   
-I/home/kielhorn/NVIDI A\_CUDA\_SDK/common/inc   
-L /lib random1.cu -o random1  
\*/

#include \<stdlib.h\>  
#include \<stdio.h\>  
#include \<string.h\>  
#include \<math.h\>  
#include \<cutil.h\>

#include “mt19937\_ref.cu” // from Eric Mills (osiris) implementation  
/\* Defines device functions:  
mt19937si() // initializer  
mt19937s()  
mt19937sl()  
mt19937gi() // initializer  
mt19937g()  
mt19937gl()  
\*/

#include “mt19937\_gold.cpp” // from Eric Mills (osiris) implementation  
/\* Defines functions:  
init\_genrand()  
genrand\_int32()  
\*/  
typedef unsigned int Uint;

// parameters  
const Uint N\_BLOCKS = 500; // Number of blocks in CUDA grid  
const Uint N\_THREADS\_PER\_BLOCK = 50; // Number of threads in each CUDA block  
const Uint RAND\_SEED = 37; /\* 37 is an arbitrary seed. Any number could be used.  
You could use time(NULL). \*/

// computed constants  
const Uint BLK\_SEED\_ARRAY\_SZ = N\_BLOCKS \* sizeof(Uint); // seed array size

Uint\*  
create\_block\_seed\_array()  
{  
// Load h\_bseeds with random unsigneds, and copy to (device) d\_bseeds  
// Return a pointer to the device array.

Uint h\_bseeds[N\_BLOCKS]; // array of block-seeds for host  
Uint _d\_bseeds; // array of block-seeds for device  
// initialize (non-parallelized) RNG  
init\_genrand(RAND\_SEED); // init genrand\_int32()  
// load h\_seeds[] with randoms;  
for(Uint i = 0; i \< N\_BLOCKS; i++){  
h\_bseeds[i] = genrand\_int32();  
}  
// allocate d\_bseeds on device  
CUDA\_SAFE\_CALL( cudaMalloc((void_\*)&d\_bseeds, BLK\_SEED\_ARRAY\_SZ) );

// load d\_bseeds with values in h\_bseeds  
CUDA\_SAFE\_CALL(cudaMemcpy(d\_bseeds, h\_bseeds, BLK\_SEED\_ARRAY\_SZ, cudaMemcpyHostToDevice));

// return a pointer to (device) array of randoms of size blockDim  
return d\_bseeds;  
}

/\*-----------------------------------------------------------  
Kernel based on shared memory and no more than 227 threads. \*/  
**global** void  
shared\_mem\_227\_kern( const Uint block\_seeds )  
{  
// initialize MT state for this CUDA-Block using a seed from block\_seeds  
mt19937si( block\_seeds[blockIdx.x] ); // shared mem initializer

```
// get random 32-bit ints
Uint random1 = mt19937s(); // version limited to 227 threads
Uint random2 = mt19937s(); // get another, etc.

/* ... your kernel-code here ... */

```

}

/\*-----------------------------------------------------------  
Kernel based on shared memory and unlimited numbers of threads \*/  
**global** void  
shared\_mem\_unlimited\_kern( const Uint block\_seeds )  
{  
// initialize MT state for CUDA-Block  
mt19937si( block\_seeds[blockIdx.x] ); // shared mem initializer

```
// get random 32-bit ints
Uint random1 = mt19937sl(); // version with unlimited threads
Uint random2 = mt19937sl(); // get another, etc.

/* ... your kernel-code here ... */

```

}

/\*-----------------------------------------------------------  
Kernel based on global memory and no more than 227 threads. \*/  
**global** void  
global\_mem\_227\_kern( const Uint block\_seeds )  
{  
// initialize MT state for CUDA-Block  
mt19937gi( block\_seeds[blockIdx.x] ); // global mem initializer

```
// get a random 32-bit int
Uint random1 = mt19937g(); // version limited to 227 threads
Uint random2 = mt19937g(); // get another, etc.

/* ... your kernel-code here ... */

```

}

/\*-----------------------------------------------------------  
Kernel based on global memory and unlimited numbers of threads \*/  
**global** void  
global\_mem\_unlimited\_kern( const Uint block\_seeds )  
{  
// initialize MT state for CUDA-Block  
mt19937gi( block\_seeds[blockIdx.x] ); // global mem initializer

```
// get a random 32-bit int
Uint random1 = mt19937gl(); // version with unlimited threads
Uint random2 = mt19937gl(); // get another, etc.

/* ... your kernel-code here ... */

```

}

int  
main()  
{  
Uint \*d\_bseeds = create\_block\_seed\_array();

const dim3 n\_blocks(N\_BLOCKS);  
const dim3 n\_threads\_per\_block(N\_THREADS\_PER\_BLOCK);

// Example kernel-calls  
shared\_mem\_unlimited\_kern\<\<\< n\_blocks, n\_threads\_per\_block \>\>\> (d\_bseeds);  
shared\_mem\_227\_kern \<\<\< n\_blocks, n\_threads\_per\_block \>\>\> (d\_bseeds);  
global\_mem\_unlimited\_kern\<\<\< n\_blocks, n\_threads\_per\_block \>\>\> (d\_bseeds);  
global\_mem\_227\_kern \<\<\< n\_blocks, n\_threads\_per\_block \>\>\> (d\_bseeds);

cudaFree(d\_bseeds);  
}

---

<div class="post-metadata">

**Author:** ![zaz](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@zaz](https://forums.developer.nvidia.com/u/zaz)\
**Post date:** [May 28, 2009, 8:04pm UTC](https://forums.developer.nvidia.com/t/more-on-cuda-random-numbers/9627/2 "2009-05-28T20:04:15Z")

</div>

The version of Mersenne Twister discussed here is based on pseudorandom seeds for each thread, and is simpler to use than that presented in the CUDA-SDK where files must be generated by spawnTwister.c and then read as part of the initialization. What is the down-side of doing this? How does the quality of the pseudorandoms compare with that of the SDK version?

–zaz

---

<div class="post-metadata">

**Author:** ![neocortex](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@neocortex](https://forums.developer.nvidia.com/u/neocortex)\
**Post date:** [July 2, 2009, 7:27pm UTC](https://forums.developer.nvidia.com/t/more-on-cuda-random-numbers/9627/3 "2009-07-02T19:27:51Z")

</div>

good post. However, it should be corrected that a pseudorandom seed is for every block not thread.  
I’m surprised there isn’t a clean API in cuda to call to generate random numbers (thinking of rand() and randn() on matlab)
