Repeatable random processes and multithreading

Status
Not open for further replies.

technophile

Ars Legatus Legionis
23,768
The title probably doesn't make a lot of sense, so let me lay out what I'm doing. I'm in the early stages of creating a framework for generating test data for a specific problem domain. One of the requirements is that a set of test data be easily re-generatable, i.e. if I create a set of test data, and then I want to provide the data set to someone else easily, or be able to regenerate that specific test data again, that's possible.

For various reasons, random selections are important in this process (to create reasonable variation from one run to the next). I would also like, for performance reasons, to be able to parallelize the process (i.e. I need to generate 1M records, spin up 8 threads that each do 125k records).

The simplest thing I can think of is to simply store (or at least display) the seed used for the RNG as part of each run, and allow the user to optionally provide a seed as input to a run. The project is being written in C# 4.5; it's a green field project and I have a lot of latitude to select libraries etc if necessary.

The conundrum I have is this:

Should I pass the seed around to the various classes that use Random to generate data, or pass the Random instance itself? Passing the seed seems a lot simpler with respect to thread safety etc, but seems problematic in other ways -- namely that if I kick off 8 threads with the same seed that are running the same operations in the same order, all 8 threads will produce identical output. :p

On the other hand, if I pass an instance of Random around, it seems I would have to use locks to synchronize access to it, and based on how frequent accesses to it are likely to be, there would be a lot of contention -- at which point it might not be any kind of performance win to parallelize at all (although if I'm streaming the output to disk at the same time, I/O might insert enough delays and pauses to rescue me). (Edit: I just realized that this would destroy the "repeatable" portion itself as there would be no way to guarantee that the threads called the Random instance in the same order. :facepalm:)

Is it worth trying to parallelize all this, and is there a good way to deal with the "repeatable random" nature desired of it, or should I just assume that parallelizing it is a hard problem and move ahead with just sharing a Random instance?
 

uec0

Smack-Fu Master, in training
68
I'm not an expert, but I know just enough to understand good parallel pseudo-random number generation is non-trivial. However, it's also a fairly common issue and isn't really "that bad" (depending on your needs).

Sharing a single random stream amongst parallel consumers has obvious synchronization issues. Also, as you've realized, thread scheduling can mess with reproducibility.

If the amount of required random numbers per thread is known or bounded, you can pre-generate your random numbers from a single random stream and distribute them amongst the threads. This may be impractical if the amount of required random numbers per thread is very large or unbounded.

Some random number generators may support substreams so that you can have multiple instances on the same random stream starting at different indices within the stream. This lets you avoid pre-generation and synchronization issues. However, you will still have problems if the amount of required random numbers is very large or unbounded.

Another possible issue with using a single stream is periodicity. Good random number generators will have large periods, but "large" is relative, depending on your use case.

Another solution is to use different random streams (initialized using different seeds) for each thread. However, using different seeds does not necessarily guarantee independence for the streams. Some methods might be able to provide independent streams. Guaranteed independence may not be that important to you.

http://www.cs.berkeley.edu/~mhoemmen/cs ... s/prng.pdf
 

bash666

Ars Legatus Legionis
24,417
The simplest thing to do woudl be to use a random number generator with a very large period, something like the Mersenne Twister (2^19000+), and then seed N RNGs, one per thread, using RtlGenRandom (http://msdn.microsoft.com/en-us/library ... 94(v=vs.85).aspx ). The probability of a collision is effectively 0. You can store the N state vectors so you can exactly reproduce the experiment if needed.
 

bash666

Ars Legatus Legionis
24,417
[url=http:/civis/viewtopic.php?p=27225433#p27225433:ks9dbyz5 said:
uec0[/url]":ks9dbyz5]

If the amount of required random numbers per thread is known or bounded, you can pre-generate your random numbers from a single random stream and distribute them amongst the threads. This may be impractical if the amount of required random numbers per thread is very large or unbounded.

You don't even need to pre generate the random numbers - he can just save the RNG state every 125k draws and then use the states to restore the RNG.
 

technophile

Ars Legatus Legionis
23,768
The requirement for randomness is just to provide variation across the test data (basically, I'm generating test data for a domain where using production data is illegal for privacy reasons, and scrubbing production data is difficult/undesirable). I don't need crypto-level randomness, just something I can feed into a weighted sample algorithm to decide whether a student is male or female, whether they live with parents or a guardian, etc.

Thanks, I'll look at RtlGenRandom and see if I can find a good C# Mersenne Twister implementation.
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
Personally, I would tend to want to break up the data-generation work from the test-running work.

Primarily because I really doubt that you will be able to get away with using 100% randomly generated data every time. I highly suspect that down the road there will be cases where you need something like "a household with 6 females and 9 cats" to reproduce a bug. If your testing system relies on generating the data from scratch every time, you're going to have to shoe horn in a way to add the records you need.

On the other hand, if you just feed previously generated data sets into a testing environment, then you just need to add the right records to the data files and run your tests.

Calling (potentially) multiple Random instances between multiple threads seems like a recipe for non-deterministic test results, which is just evil.

I don't see how you could make it deterministic between multiple threads reliably. Sure each thread is going to generate the same data from the same seeds, but the actual order of the data hitting the thing-being-tested is going to depend on which threads get responses first, etc. If all your threads are pulling previously generated data from a single producer, then the data hitting the back end should be the same, and in the same order, run after run, which would be a requirement, IMHO.
 

technophile

Ars Legatus Legionis
23,768
[url=http:/civis/viewtopic.php?p=27231535#p27231535:3tx3mbb9 said:
Faramir[/url]":3tx3mbb9]I thought the whole framework was just for generating test data? If you need to generate a million independent records and each of 8 threads generates 125k records, what difference does it make how the records are interleaved when writing to the database?
Correct, I'm not running any tests here, just generating test records. The records won't be inserted into any database, they'll be dumped into XML files (for various reasons, none of which are worth discussing here), but even if I have 8 threads dumping 8 different XML files, reassembling them into a single file will likewise not be difficult (for various reasons, none of which are worth discussing here ;)). (In specific, any given record has an ID that is generated from a start value and an increment; if I'm running 8 different threads, I'd just pass them start values that are 125k apart, and then use the IDs to interleave them in the correct order in the output file.)

The case where I need data to fit a particular pattern is already considered; we'll be using representative data templates for these (the easiest example is probably student attendance patterns; we could generate random attendance data, but it wouldn't look realistic and wouldn't play well with the analytical processes that identify students who are struggling in school due to things like that). I'm only concerned with how to produce stochastic data (like student gender, selection of a given name from a list of allowable names, grade distribution, etc) here.



I'm not actually doing the parallelized version yet, but I'd like to at least consider how it might be done so that when I hand in this project and they ask how it can be made to perform better, I have some options (with some estimates on what that will take) to answer with. :)
 

minnmass

Ars Tribunus Militum
2,087
Subscriptor
A Full Cycle algorithm (the algorithm that things like iTunes uses to "play all, randomly") might be helpful.

Basically, you create an "array" of all possible values, then choose a prime number which is not a factor of the length of the array and a random starting point in the array. The "next" index is the current index plus the prime number, mod the number of elements in the array.

next = (current + prime) % length; // note: make sure that (current + prime) don't overflow, too

That guarantees that all numbers will be seen in a "random" order (for shuffling music, it helps to randomize the array first). Ensuring that you don't keep looping over the same elements is left as an exercise...

If you give each thread its own prime and seed, you can have all of the threads spin through their own unique ordering of the X IDs.

Of course, you need to do something (somewhat) clever with the resulting numbers; the numbers will almost always toggle between even and odd, and will generally tend to increase (unless "prime" is particularly large, in which case numbers would tend to always decrease). Maybe something like basing the gender on the number of bits that are set in the resulting number (1 and 2 would be "male", 3 would be "female", etc.), or bit-shift the resulting number to make it smaller...

Anyway, that'd let you save 8 sets of "seed + prime" and a single length value to re-create a randomly-created data set.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Whatever you do (good advice here already) do NOT use Random or any other externally supplied library to do the randomness unless it guarantees determinism across platforms/Debug+Release builds/past and current versions/other variables unforeseen.

Mersenne Twister has code in innumerable different languages and is easy to get to be repeatable across them for the same seed so long as the language is well defined (with C it's *much* harder to be sure), just make sure the generator itself has sufficient entropy, state, bias to actually cover all your requirements. As a common example of failing at the latter 32bits is not enough to produce every permutation of a shuffled deck of cards...
 
Status
Not open for further replies.