Creating predictable PRNGs per Rayon task from a master PRNG

#1

Hi guys, I am planning to write a ray tracer in Rust. One of the requirements of doing so is to have PRNGs per thread, each seeded with a unique number. The PRNG does not need to be cryptographically secure, but has to be statistically good. I am planning to use the Pcg64Mcg PRNG everywhere in a hierarchical fashion: one master PRNG, and each spawned slave PRNG inside a thread would take its seed from the master PRNG. This would satisfy all the criteria for reproducibility and good quality pseud-random numbers.

I am planning to use Rayon and the rand crates for this.

On doing some searching, it seems there has been some activity on both Rayon and rand sides to add support for each:



However, there does not seem to be any documentation in either crates on how to leverage this. If someone could provide some pointers on how to do it, or point to some example resources/documentation, it’d be great! I’m still quite beginner to Rust so any help would be appreciated!

#2

Yeah, I’m not sure we came to any useful conclusions in those threads.

If you need determinism, I think you’ll do best to isolate the PRNGs from the whims of Rayon’s dynamic splitting and work stealing. For instance, in a ray tracer you may choose to parallelize the image by rows. You could prepare separate PRNGs dedicated to each row, and simply zip those with the row iterator. This way, no matter how Rayon decides to send data between threads, the PRNG use will be consistent.

#3

I think the easiest approach will be to pre-generate random seeds for each ray (which should be very fast) and then pass it to rayon. Or even simpler you could enumerate rays and use this number (maybe xored or added to some constant) as a PRNG seed.

#4

Thank you very much for the both replies! I will keep both of these in mind.A possibly good approach also seems to use something like the index of the pixel being raytraced as the seed, and use that when spawning an PRNG for each pixel.

For me, what’s most important is that no two sets of workloads in rayon should use the same seeded PRNG, and that all of that should be reproducible.

Thanks again for the suggestions!