163 points · by marcobambini · 6y ago · 118 comments
Response by the author: https://www.pcg-random.org/posts/on-vignas-pcg-critique.html
Personally, I use a SIMD Xoshiro256+ when I want a solid and fast RNG (although I mostly use Julia's default -- a MersenneTwister).
My use cases are Monte Carlo, where "passes statistical tests" is probably all that's needed for good results. Maybe I should just try an mcg.
https://chasethedevil.github.io/post/war-of-the-random-numbe...
PCG is also not that good. There do exist proper and fast PRNG's though. DSFMT has the same problems as MT. I'm just adding some of them to gsl and dieharder btw.
One property I anecdotally observed about it is that it is a little sensitive to the values you choose for its seed. Too many zero bits or making two generators with nearly-identical seeds would create visible correlation in the outputs. It worked much better if all values were hashed before using them for seeding.
Hence any cryptographic use of PCG is definitely prohibited
[0]: http://www.thesalmons.org/john/random123/papers/random123sc1...
- [1] https://github.com/mratsim/weave/issues/147
- [2] https://github.com/mratsim/trace-of-radiance/blob/99f7d85/tr...
- Usage for parallel raytracing: https://github.com/mratsim/trace-of-radiance/blob/99f7d85/tr...
Beyond the JAX paper, the Pedigree-based RNG from Leiserson was interesting as well:
- http://supertech.csail.mit.edu/papers/dprng.pdf
- https://pdfs.semanticscholar.org/a32c/3b7b8d5d3ebd594bea2d9c...
And Haskell's splittable RNG:
- http://www.hg.schaathun.net/research/Papers/hgs2015jfp.pdf
- http://publications.lib.chalmers.se/records/fulltext/183348/...
https://chasethedevil.github.io/post/more-on-random-number-g...
Statistical Quality
PCG Family Excellent
ChaCha20 Good
What a joke.> Fewer rounds result in poor statistical performance; ChaCha2 fails statistical tests badly, and ChaCha4 passes TestU01 but sophisticated mathematical analysis has shown it to exhibit some bias. ChaCha8 (and higher) are believed to be good. Nevertheless, ChaCha needs to go to more work to achieve satisfactory statistical quality than many other generators.
* too slow (for a scant few applications)
* too much state & code (for a scant few applications)
* can’t find a nice implementation (there are some, though)
Everything else written there is FUD. And this whole "statistical tests" thing is a red herring anyway. There’s a field that concerns itself with "statistical quality"—it’s called cryptography. They have plenty sophisticated mathematical analysis.
Cryptographic RNGs achieve their strength through large round-counts. ChaCha runs 20x quarter rounds of its algorithm, which means you're basically doing:
randomNumber = hash(hash(hash(hash...hash(seed)))))))))))
After 80-iterations of your hash function, you'd HOPE it was random looking!! In effect, cryptographic RNGs are built for safety, and have huge safety margins.
---------
The "natural" approach to making a non-secure (but faster) RNG is to reduce the hash rounds to a single cycle. IE: instead of running 80-quarter rounds of ChaCha, why not just run 1x quarter-round of ChaCha?
Well, it turns out that 1-round of ChaCha20 is utter crap. Completely crap, worse than a LCGRNG.
------
AES is similarly designed for 8+ rounds. In my experiments, it took 4 or 5 rounds before AES would achieve a decent distribution of bits!!
It took a fair bit of effort for me to turn AES into a random number generator. I analyzed AES's bit-flow, and designed a "counter function" that worked well with AES's single-round weakness. Even then, I never accomplished a 1-round of AES RNG, I had to use 2-rounds of AES to make a decent bit distribution.
In particular: 1-round of AES is only designed to shuffle bits across a 32-bit DWORD. You need the 2nd round (or more) to shuffle the bits to the whole 128-bit group. (That is: the "MixColumns" and "ShiftRows" step of AES, which only really take effect on the 2nd round or later).
-----
If anyone could figure out a special "seed" function that can work with AES's single-round weakness, they probably can make a much faster RNG than what I accomplished. Or maybe, people can just be "happy" with 32-bits of well-shuffled bits? A 32-bit RNG (with 128-bit seed) is probably still useful to somebody.
Secondly, ChaCha1–7 aren’t a thing, outside of a cryptanalysis paper anyway. Primitives like ChaCha need a certain number of rounds to do what they do.
Finally, ChaCha8 doesn’t just “pass statistical tests,” it’s cryptographically secure.
The reason nobody uses it like that is that it is slower than most other PRNGs
- Statistics,
- Deep Learning,
- Monte-Carlo simulation (finance, reinforcement learning, game AI, raytracing).
- Fuzzing
- Load balancing
- Peer selection (if non adversarial, otherwise use a CSPRNG)
Also non-determinism of CSPRNG (and floating points) would a huge issue for debugging machine learning models:
- https://www.twosigma.com/insights/a-workaround-for-non-deter...
- https://github.com/tensorflow/tensorflow/issues/3103
- https://discuss.pytorch.org/t/deterministic-non-deterministi...
- https://github.com/tensorflow/tensorflow/issues/2732
Chacha8 has a throughput of 2GB/s and xoshiro256++ has a throughput of 8GB/s
For Monte-Carlo, the RNG is definitely the bottleneck. For load balancing of short tasks the RNG is the bottleneck.
What is questionable is the "somewhat secure" argument. Either you don't want adversaries to predict your numbers and you should use a good CSPRNG, or you don't care and predictability is not a property that matters.
As for reproducibility, all PRNGs give a reproducible sequence if you know the internal state, including the secure ones. You have to mix in a source of entropy to make them non-deterministic. The predictability we are considering here is when the attacker doesn't have access to the internal state.
What makes PCG attractive for microcontrollers is really that it's of known good quality, its implementation is very small and very simple, and it ends up generating efficient code for 32-bit processors (i.e., ARM Cortex-Ms). That is not, and can not ever be, true for something like a 128-bit shift register. PCG is great for just tossing in when I'm working on a platform that has no built-in library rand() function, or where it's busted, or whether I don't want to bother figure out if/how badly it's busted. (With how easy PCG is to use, that last one covers every embedded platform ever....)
PCG is not the best RNG out there: it's not the highest quality, it's not the fastest, it's not the least predictable, it's not the strongest theoretically. (It isn't the smallest, either, but it's quite small and the smaller RNGs I know of are either code-golfed, which doesn't count, or truly garbage.) But it is a nice equilibrium between all of those things. And did I mention it's simple? Simple is really, really nice to have :)
I'd suspect the majority of random numbers generated in the world don't need crypto, they need speed. The world's supercomputers are not doing crpyto, they're doing simulations. Most people are not doing crypto most of the time - and when they're gaming in any manner, no need to pay csprng tax.
The only place one should use a csprng is for adversarial situations.
Use the right tool for the job, correct?
There is a time and place for non-CS rngs, and it is in randomized methods whos correctness/results does not rely on the RNG.
[1] "Pattern" section here: http://builder.openhmd.net/blender-hmd-viewport-temp/render/...
http://extremelearning.com.au/unreasonable-effectiveness-of-... (yes, no HTTPS, but incredibly illustrative)
Discussed in 2018: https://news.ycombinator.com/item?id=17873284
A good non-cryptographic random number generator like xoshiro256 can generate at 4 times the speed of a chacha20 random number generator. Depending on how many models you need to compute and the desired precision of those models and how many random samples you need per model, this can easily be the difference between hours and days, or days and weeks.
Whenever a post on PRNGs comes up, I'm reminded of this post from a while back about Chrome:
https://medium.com/@betable/tifu-by-using-math-random-f1c308...
Near the end is a Monte Carlo estimate of Pi using 10^10 iterations:
Chrome 3.1418697000 0.0002770464 1301.903s
Firefox 3.1416998084 0.0001071548 249.595s
Safari 3.1416692728 0.0000766192 7172.207s
The first observation is that the error was significantly higher for Chrome. The second is that Safari, which apparently did use a CSPRNG, was an order of magnitude slower. If you let Firefox run that long, I imagine that it would have performed many more iterations, resulting in much lower error.That's around 30x slower than a decent version of PCG, which also has a lot of variants to cover a lot of use cases.
For MC path tracing (graphics) this is at least an order of magnitude too slow.
Sibling comments are completely correct. Graphics simulations often require quasirandom sequences; the particular sequence is not important, but any correlations in the sequence will be visible in the output as artifacts, so we want a decorrelated sequence.
If this is not enough of a real-world example for you, then Monte Carlo methods also show up in weather modeling, financial planning, and election forecasting. In those predictive systems, there is extreme uncertainty and dependence on initial conditions, which we model with quasirandom sequences and seed numbers respectively. By running many simulations with different random sequences and then examining all of the results statistically, we can get good estimates of future behavior.
Edit: Oh, you're not in good faith. Okay, cool story. Best of luck with whatever imaginary idea of "unpredictability" you're trying to define, but you might want to return to actual maths at some point.
For example you can increase the quality of a RNG sequence r(n) by adding a multiplicative hash, r'(n) = A r(n) for some good constant A. A consumer treating r' as a blackbox expects B r'(n) = AB r(n) to be a good random sequence, but if B is close to the inverse of A, the constant AB may no longer be "good".
There is no need to cryptographic strength, which is costly, and pseudo-randomness is enough and much cheaper.
People was later able to use the leaked, alleged rc4 algorithm to decrypt messages encrypted by Notes. That basically confirmed that the algorithms are the same.
I use it to deal tiles in my version of online Azul: https://tiles.kevincox.ca
I also used it to simulate the Red7 game for strategy testing: https://gitlab.com/kevincox/red7-sim
I am not fluent in C or Rust and time constrained, otherwise I would have taken a shot at it
https://raw.githubusercontent.com/shlomif/fortune-mod/master... https://raw.githubusercontent.com/wapm-packages/fortune/mast...
Or better, with an entropy source like rdrand or rdseed?
The main use for rdrand is to mix it with other entropy sources to produce a seed for another rng.
https://observablehq.com/@jrus/permuted-congruential-generat...
It’s a bit of a pain because Javascript can’t do native 64-bit integer arithmetic. But it should still be fast enough for most purposes.
They are a neat theoretical construction however I believe they have some serious flaws when attempting to split and construct multiple streams.
Honestly though RDRAND is cheap enough that I'd take true randomness over determinism.
Nice!
but I still need to add more tests to get a better quality comparison against the xoshiro's
Can an algorithm really produce a non-reproducible result?
> The BSD implementations (which are the only widely used ones) have several additional issues
> • No facility for a user-provided seed, preventing programs from getting reproducible results
> • Periodically “stirs” the generator using kernel-provided entropy; this code must be removed if reproducible results desired (and is removed from the C++ adaptation I created for testing purposes)
In a more direct sense, yes. If you're allowed to keep secrets (like internal state), it's possible to produce random numbers algorithmically for certain (weak) definitions of random, even with a deterministic machine. A simple example of this would be sequential bits of a normal number. As you strengthen your definition of randomness you pretty quickly get into non-computable territory though.
#1: Have a "counter" of some kind. The simple counter trivially creates a maximum length cycle. "seed++" is one such counter.
#2: Have a "hash" that converts the counter into a random number, using a 1-to-1 bijection. There are a great many 1-to-1 bijections.
So your RNG is basically:
oldSeed = seed;
seed = counterFunction(seed);
return hash(oldSeed);
------------I used this methodology to make a pretty fast generator myself. The coding was done in a weekend, but it took some weeks to test: https://github.com/dragontamer/AESRand
For AESRand:
"counterFunction" is a SIMD 2x64-bit Add over the XMM register. I chose an odd number arbitrarily (which are just the first 16 prime numbers: 0x01030507...), which will trivially cycle after 2^64 numbers.
"hash" is aesenc(aesenc(seed, constant), constant), where constant is an arbitrary (chosen to be the same odd number that was used in the "counterFunction" step). The 2nd parameter to aesend is just an XOR.
I also run a 2nd parallel aesdec(aesenc(seed, constant), constant) to generate a 2nd set of 128-bit random numbers, for 256-bits to be made across the hash. Yes, a 128-bit seed "hashes" into a 256-bit random number. Since this passes statistical tests, its probably fine, and this is a good source of instruction-level-parallelism.
All in all, I achieved 30GB/sec random numbers. Or 256-bits of random numbers every 3.7 cycles that passes BigCrush, TestU01, and PractRand.
--------
AES is a 1-to-1 bijection: that's a necessary condition for AES to be decoded. Though I use AES, this function is NOT cryptographically sound. I'm just using AES because its the fastest high-quality bijection in the entire modern CPU instruction set. x86, ARM, and POWER9 all implement single-cycle AES instructions.
It is possible to write a portable AESRand across the different CPUs (ARM, x86, and POWER9). I got far enough to prove that its possible, but then my real work started to ramp up and I had to drop this hobby project. Its very tricky to do so: ARM, x86, and POWER9 implement AESENC slightly differently: shuffling the fundamental steps in different ways.
Or in the case of POWER9, it executes in big-endian mode instead of little-endian (like ARM / x86). Redesigning the algorithm to be portable across the shuffled "SubBytes" and "MixColumns" steps between the CPUs is tricky but possible.
Lets take PCG's author's comments one by one:
https://www.pcg-random.org/posts/cpp-seeding-surprises.html
Re: Predictability. I don't care. Truely. If unpredicatablity is important, the application must use a cryptographic random number generator. Those are the only known family that are hard-to-predict. Valuing un-predictabiltiy from a non-cryptographic PRNG has always been one of PCG's demerits in the xoshiro-versus-pcg debacle.
Re: Seed_seq's problems. The biases she's making out to be catastrophic are really quite small. In actual scientific monte carlo simulations, they don't affect things at all. I want to know the difference between 10^6 floats generated from the gaussian distribution, one with seed-seq's optimally seeded and one with it sub-optimally seeded. Because the "motivating scenario" isn't. You shouldn't ever be using a PRNG if all you need is one random number. You just grab a seed from a strongly-random generator like /dev/random.
The argument about seed_seq failing to be a bijection is completely irrelevant. You just need it to uniquely select one internal state of MT from the one initial value. So long each sequence of the first 600-someodd values drawn from it are unique, you've done that.
The demonstrated bias in MT's initial conditions doesn't matter one whit.
Concepts and modules (supposedly) fix these issues, and I'm not going to use ranges again until those two are very mature features of C++. Even if you ignore this stuff, it's incredibly "C++ified" in just the worst way, with incredibly obtuse templates and type concepts all over the place.