March 3, 2011

Random number generators on GPU

Almost every simulation requires random numbers generation (RNG) for achieving accurate results. In my simulations I used 2 RNGs. MersenneTwister - has a very long period and can be used in simulations that are supposed to be running for a long time, and XOR128 - extremely fast RNG, however its period is not as large as MerseneTwister's one. I created a small library that contains 3 RNGs: MersenneTwister, XOR128 and Tausworthe generator.

For implementing MersenneTwister I deeply modified NVIDIA's sample. Each thread in a grid runs its own RNG. States are kept in a global memory. Each thread is supposed to read a state in the beginning of execution and save it at the end. I have a helper classes, which do it.
The library is available at link. And it contains an example file, however I'm going to put some small tutorial here.

The library consists of 2 parts - device and host.

Device code for RNGs is defined in files:

mtwister.cuh - for MersenneTwister
rndfast.cuh    - for XOR128 and Tausworthe

So if you want to use these generators in your projects you just need to include one of these files in your CU file. Then in kernels you can use generators like this (MersenneTwister example):
const int maxValue = 1024;
const int tid = blockDim.x*blockIdx.x + 
                 threadIdx.x;

MTGenerator gen(tid);

int   intNum   = gen.GetInt(maxValue);
flaot floatNum = gen.GetFloat();
If you want to use other generators just use classes TausGenerator for Tausworthe and Xor128Generator for XOR128.

You will also need to initialize seeds. These functions are defined in files:

mtwister.h - for MersennwTwister
seedgen.h   - for XOR128 and Tausworthe

Simply call one of these functions for initialization:
void InitGPUTwisters(const char* fname, 
                     int numGen, int seed);
void InitFastRngs(int numRngs);
And one of these functions for deinitialization:
void DeinitGPUTwisters();
void DeinitFastRngs();

Again, there is a good example in the package, so feel free to download and use it. If you have any questions, please send me an email or comment.

1 comment:

Unknown said...

Hello there!

I'm sorry to ask, but can't you reuplode the library please? Your link is already broken. :(
And I'm a bit confused with seeds initialization. Where should I get a start data file for InitGPUTwisters? I found several implementations of MersenneTwister on GPU, but no way how to generate it. :O

Best regards,
Helen