By using the tf.set_random_seed() method one can set the graph wide seed for random number generation.
However, I'm unsure whether/how this graph wide seed is working when multi-threaded execution is turned on by using inter_op_parallelism_threads > 1 and intra_op_parallelism_threads > 1 switches.
Question: After graph wide seeding using tf.set_random_seed() is the tensorflow random number generation process still deterministic when multiple operations are executed in parallel? Especially in the case when multiple random number generation ops are executed concurrently.
Related
I hope you are well!
I use random numbers that depend on time for my encryption.
But this makes my encryption hackable...
My question is how can I make randoms that are not the same every time after running the randoms and also do not use seed time.
Most of the time we randomize like this:
srand ( ( unsigned ) time ( 0 ) );
cout << "the random number is: " << rand() % 11;
But we used time here and the hacker can understand the random numbers by having the program run time.
srand and/or rand aren't suited to your use at all.
Although it's not 100% guaranteed, the C++ standard library provides a random_device that's at least intended to provide access to true random number generation hardware. It has a member named entropy() that's intended to give an estimate of the actual entropy available--but it can be implemented as a pseudo-random number generator, in which case this should return 0. Assuming entropy() returns a non-zero result, use random_device to retrieve as much random data as you need.
Most operating systems provide their own access to random number generation hardware. On Windows you'd typically use BCryptGenRandom. On UNIXesque OSes, you can read an appropriate number of bytes from /dev/random/ (there's also /dev/urandom, but it's potentially non-blocking, so it could return data that's less random if there isn't enough entropy available immediately--that's probably fine if you're simulating rolling dice or shuffling cards in a game or something like that, but probably not acceptable for your purpose).
There are pseudo random number generators (PRNG) of very different quality and typical usage. Typical characteristics of PRNGs are:
The repeating period. This is the number of different numbers, that a PRNG can produce and for good generators this is almost always two to the power of the bitwidth.
Hidden patterns. Some bad PRNGs have hidden patterns. Obviously they decrease the quality of the random numbers. There are tests, that can be used to quantify the quality in this regard. This property, as well as the speed are mainly important for scientific usage like monte carlo simulation.
Cryptographic security. For cryptographic operations there is the need of special PRNGs with very specific use cases. You can reed more about them for example on wikipedia.
What I am trying to show you here, is that the choice of the right PRNG is just as important as the right choice of the seed. It turns out that the C rand() performs very bad in all three of the above categories (with exception maybe of the speed). That means if you seed rand() once and repeatedly call it and print say rand() % 11, an attacker will be able to synchronize to the PRNG after a short period of time even if you used the most secure and random seed. The rand() as well as most other, better random generators in the C++ standard library, were designed to be used for scientific calculations and are not suitable for cryptographic purposes.
If you need cryptographically secure random numbers I would suggest you to use a library that is build for exactly that purpose. A widely used crypto library, that can be used cross platform is OpenSSL. It includes a function called RAND_bytes() that can be used for secure random numbers. Do not forget to carefully read the manual page if you want to use it. You have to check the return value for errors!
I am trying to create a password generator. I used the random library, and after reading the documentation, I found out that rand() depends on an algorithm and a seed (srand()) to generate the random number. I tried using the current time as a seed (srand(time(0))), but that is not truly random. Is there a way to generate truly random numbers? Or maybe get the current time very accurately (like, in microseconds)? My platform is Windows 10 x64.
No, these are not truly random numbers. True randomness requires hardware support. Typically they work by sampling an analoge generated white noise signal.
Probably you want to seed your random generator with an always different value. A time() call would do it, or you can also hash it by the current pid ( getpid() ).
It is true that PCs cannot generate truly random numbers without dedicated hardware, however remember that each PC has at least one hardware random generator attached to it - that device is you, the user sitting in front of the computer. Human is a very random thing. Each one has its own speed of key presses, mouse movement patterns etc. This can be leveraged to your advantage.
On Linux you have a special device, /dev/random which uses exactly this. While you work on the PC, it collects random data (not security sensitive of course), such as how fast you tap the keyboard, and in addition hardware related data, such as intervals between interrupts, and some disk IO info. This all generates entropy, which is later used to generate pseudo random data, which is still not 100% random, but is based on much stronger random seed.
I am not an expert on Windows, but a quick search shows that Windows provides CryptGenRandom API, with somewhat similar functionality.
If you want to generate cryptographically strong random data, I suggest you start from this. Remember, this is still not as strong as dedicated hardware random generator. But this is good enough for most real world use cases.
If you are using rand() to generate a password as per your question then I suggest you use some kind of cryptographic method as they will be much stronger and collision-resistant than the numbers generated by rand(). Use something like Openssl or something similar to that kind.
If not, then truly random numbers as suggested by 'peterh' need hardware support. Yet you can use much better functions than rand() such as Mersenne Twister. It is a better generator than rand() as rand just uses a simple linear congruential generator. Read about mt_19937 here
I tried using rand() function to create random numbers in each thread in a multi-threaded C++ program. I ended up getting much worse results as I was increasing the number of threads. Thanks to this post, I found that because it needs to keep track of the states, rand() uses a lock for every call.
Does using C++11 random library (this usage as an example) do the same procedure and I should expect the same observation if I use it? Or C++11 can provide a way around?
Yes and no. Most of the C++11 random number generators are objects that encapsulate their own state, so as long as you create a separate generator object for each thread, each should be able to operate independently of the others (so you don't need any locking).
The specific case of std::random_device is a little different though: this is intended (but not guaranteed) to obtain truly non-deterministic data from some sort of random number generation hardware. The driver for that device may well impose locking requirements of its own -- and it's often fairly low bandwidth as well, so if you want to obtain a lot of numbers quickly, it's usually a poor choice.
In a typical case, you want to use one generator (other than std::random_device) per thread, and use std::random_device only to provide the initial seeds for those other generators. This may impose locks during that initialization, but then allows each thread to generate its random numbers without any interlock with other threads.
I'm coding a physics simulation heavily using random numbers, I just profiled my code for the first time so I may be in wrong in reading the output but I see this line coming first:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
90.09 21.88 21.88 265536 0.08 0.08 std::mersenne_twister_engine<unsigned long, 32ul, 624ul, 397ul, 31ul, 2567483615ul, 11ul, 4294967295ul, 7ul, 2636928640ul, 15ul, 4022730752ul, 18ul, 1812433253ul>::operator()()
It seems to mean that generating number generator takes 90% of the time.
I had already written a previous post asking if not constructing the random probability distributions at each loop could save me time but after trying and timing it didn't help (Is defining a probability distribution costly? ). Are there common options for optimizing random number generation?
Thank you in advance, my simulations (in its current state) runs for days so reducing on 90% of this computation time would be a significant progress.
There is always a trade-off between the efficiency, i.e. speed and size (number of bytes of the state), on the one hand and "randomness" of any RNG on the other. The Mersenne twister has quite good randomness (provided you use a high-entropy seed, such as provided by std::random_device), but slow and has large state. std::minstd_rand or std::knuth_b (linear congruential) are faster and ranlux48 (Fibbonacci) yet faster, but are less random (pass fewer test for randomness, i.e. have some non-random spectral properties). Just experiment and test if you're happy with the randomness provided (i.e. have no unsuspected correlations in the random data).
edit: 1 All these RNG are not truly random, of course, and are also not random enough for cryptography. If you need that, use std::random_device, but don't complain about speed. 2 In parallel (which you should consider), use thread_local RNGs, each initialised with another seed.
If your code spends most of its time generating random numbers, you may want to take some time to choose the best algorithm for your application and implement it yourself. The Mersenne Twister is a pretty fast algorithm, and has good randomness, but you can always trade off some quality of the random numbers generated for more speed. It will depend on what your simulation requires and on the type of numbers you are generating (ints or floats). If you absolutely need good randomness, Mersenne Twister is probably already one of your best options. Otherwise, you may want to implement a simple linear congruential generator in your code.
Another thing to watch out for is if your code is parallel, you should be using a reentrant version of the random number generator and make sure that different threads use their own internal state variables for their generators. Otherwise, mutexes to avoid overwriting internal state variables of the generator will slow down your code a lot. Many library generators are not reentrant, mind you. If your code is not parallel, you should probably parallelize it and use a separate thread to populate a list of random numbers for your simulation to consume. Another option is to use the GPU to generate random numbers in parallel.
Here are some links comparing the performance of diferent generators:
http://www.boost.org/doc/libs/1_38_0/libs/random/random-performance.html
https://www.gnu.org/software/gsl/manual/html_node/Random-Number-Generator-Performance.html
Use a dedicated random number library.
I would suggest WELL512 (link contains the paper and source code).
Marsaglia's KISS RNG is fast and is fine for simulation work. I am assuming that you don't need cryptographic quality.
If the randomness requirements allow it, you can use the RDTSC instruction to get random numbers, e.g. int from0to9 = rdtsc() % 10.
I have a class that contains two sources of randomness.
std::random_device rd;
std::mt19937 random_engine;
I seed the std::mt19937 with a call to std::random_device. If I want to generate a number and I don't care about repeatability, should I call rd() or random_engine()?
In my particular case, I'm sure both would work just fine, because this is going to be called in some networking code where performance is not at a premium, and the results are not especially sensitive. However, I am interested in some "rules of thumb" on when to use hardware entropy and when to use pseudo-random numbers.
Currently, I am only using std::random_device to seed my std::mt19937 engine, and any random number generation I need for my program, I use the std::mt19937 engine.
edit: Here's an explanation for exactly what I am using this particular example for:
This is for a game playing program. This particular game allows the user to customize their 'team' prior to beginning a round against an opponent. Part of setting up a battle involves sending a team to the server. My program has several teams and uses the random number to determine which team to load. Each new battle makes a call to std::random_device to seed the pseudo-random number generator. I log the initial state of the battle, which includes this team that I'm randomly selecting and the initial seed.
The particular random number I'm asking about in this question is for the random team selection (where it is beneficial to not have the opponent know ahead of time what team I'm using, but not mission-critical), but what I'm really looking for is a rule of thumb. Is it fine to always use std::random_device if I don't need repeatability of my numbers, or is there a real risk of using up entropy faster than it can be collected?
The standard practice, as far as I am aware, is to seed the random number generator with a number that is not calculated by the computer (but comes from some external, unpredictable source). That should be the case with your rd() function. From then on, you call the pseudo-random number generator(PRNG) for each and every pseudo-random number that you need.
If you are worried about the numbers not being random enough, then you should pick a different PRNG. Entropy is a scarce and precious resource and should be treated as such. Although, you may not be needing that many random numbers right now, you may in the future; or other applications could need them. You want that entropy to be available whenever an application asks for it.
It sounds like, for your application, that the mersenne twister will suit your needs just fine. No one who plays your game will ever feel like the teams that are loaded aren't random.
If you are not using it for encryption it is fine and well to repeatedly use mt19937 which is seeded by random_engine.
For the rest of this answer, I assume you are using the random numbers for encryption in your networking code. In short, mt19937 is not suitable for that use.
http://en.wikipedia.org/wiki/Mersenne_twister#Disadvantages
There is a potential risk that you will leak information (perhaps indirectly) over time so that an attacker could start to predict the random numbers. At least in theory, but this is what it's about. From Wikipedia
...since this figure is the size of the state vector from
which future iterates are produced) allows one to predict all future iterates.
A simple means of preventing random number generation information to leak to the user is to use one-way hash functions, but there's much more to it. You should use a random number generator designed for that purpose:
http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator
Various examples (with code) are found here http://xlinux.nist.gov/dads/HTML/pseudorandomNumberGen.html
If you need randomness for a simulation or a game, then that you're doing is fine. Call the random device just once, and do everything else with a randomly seeded pseudo-RNG. As a bonus, you should store the seed value in a log file so you can later replay the pseudo-random sequence:
auto const seed = std::random_device()();
// save "seed" to log file
std::mt19937 random_engine(seed);
(For multiple threads, use the PRNG in the main thread to generate seeds for further PRNGs in the spawned threads.)
If you need a lot of true randomness for cryptographic purposes, then a PRNG is never a good idea, though, since a long sequence of output contains a lot less randomness than true randomness, i.e. you can predict all of it from a small subset. If you need true randomness, you should collect it from some unpredictable source (e.g. heat sensors, user keyboard/mouse activity, etc.). Unix's /dev/random may be such a "true randomness" source, but it may not fill up very quickly.
You may want to have a look at http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful that explains why you should use uniform_int_distribution, and the relatives strengths of random_device / mt19937.
In this video, Stephan T. Lavavej specifically states that on visual C++, random_device can be used for cryptographic purposes.
The answer is platform dependent. I seem to remember that with Visual C++ 2010, std::random_device is just mt19937 seeded in some undocumented way.
Of course you realize that any ad hoc encryption scheme based on a random number generator is likely to be very weak.
Assuming this is not for cryptographic purposes, the most important thing to remember about random number generation is to think of how you want the distribution of the random numbers to be and what is the range you are expecting.
Usually standard random number generators within libraries are designed to give out uniform distribution. So the numbers will range between 0 and some RAND_MAX ( say on 32 bit machine it is 2^31 -1 )
Now here is the thing to remember with pseudo random number generators. Most of them are designed to generate random numbers and not random bits. The difference is subtle. If you need numbers between 0 and 8 most programmers will say rand()%8
This is bad because the algorithm was for randomizing 32 bits. But you are using only the bottom 3 bits. No good. This will not give you a uniform distribution (assuming that is what you are looking for)
You should use 8 * (rand() + 1) / (RAND_MAX) which will now give you a uniformly random number between 0 and 8.
Now with hardware random number generators you may have random bits being produced. If that is indeed the case, then you have each bit independently being generated. Then it is more like a set of identical independent random bits. The modeling here would have to be a bit different. Keep that in mind, especially in simulations the distribution becomes important.