-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathrandomiser.cpp
More file actions
268 lines (183 loc) · 7.43 KB
/
randomiser.cpp
File metadata and controls
268 lines (183 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/** @file
* Functions for generating random numbers consistent
* between distributed nodes, used for emulating
* quantum measurements and randomly initialising Quregs.
*
* @author Tyson Jones
* @author Balint Koczor (patched v3 MSVC seeding)
*/
#include "quest/include/types.h"
#include "quest/src/core/bitwise.hpp"
#include "quest/src/core/errors.hpp"
#include "quest/src/core/validation.hpp"
#include "quest/src/core/constants.hpp"
#include "quest/src/comm/comm_config.hpp"
#include "quest/src/comm/comm_routines.hpp"
#include <cmath>
#include <complex>
#include <random>
#include <limits>
#include <vector>
using std::vector;
/*
* RNG HYPERPARAMTERS
*/
#define DEFAULT_NUM_RNG_SEEDS 4
/*
* PRIVATE RNG SINGLETONS
*
* The use of static ensures we never accidentally expose the
* singletons to other files. We must always sample/advance the
* RNGm on every node at the same time to avoid divergence of
* outcomes (producing non-L2 states), though this does not
* require communication; we just ensure rand_() funcs are
* never elsewhere invoked inside rank-dependent control flow.
*/
static vector<unsigned> currentSeeds;
static std::mt19937_64 mainGenerator;
/*
* SEEDING
*/
void rand_setSeeds(vector<unsigned> seeds) {
// this function consults only root-node seeds, broadcasting
// to other nodes which might not have the existing space to
// receive them, so we explicitly reserve the needed space
// all nodes learn root node's #seeds
unsigned numRootSeeds = seeds.size();
if (comm_isInit())
comm_broadcastUnsignedsFromRoot(&numRootSeeds, 1);
// all nodes ensure they have space to receive root node's seeds
seeds.resize(numRootSeeds);
// all nodes receive root seeds
if (comm_isInit())
comm_broadcastUnsignedsFromRoot(seeds.data(), seeds.size());
// all nodes remember seeds (in case user wishes to later recall them)
currentSeeds = seeds;
// all nodes pass all seeds to RNG
std::seed_seq seq(seeds.begin(), seeds.end());
mainGenerator.seed(seq);
}
void rand_setSeedsToDefault() {
// seeds will attempt to use device's CSPRNG
std::random_device device;
// use CSPRNG to generate well-spread seeds
vector<unsigned> seeds(DEFAULT_NUM_RNG_SEEDS);
// root node produces seeds (non-root seeds would be ignored)
if (comm_getRank() == 0)
for (auto &seed : seeds)
seed = device();
rand_setSeeds(seeds);
}
int rand_getNumSeeds() {
return currentSeeds.size();
}
vector<unsigned> rand_getSeeds() {
// returns a copy, so currentSeeds stays unmutated
return currentSeeds;
}
/*
* MEASUREMENT SAMPLING
*
* which is always consistent between nodes, as
* maintained by identical seeding and RNG advancing
*/
int rand_getRandomSingleQubitOutcome(qreal probOfZero) {
// assumes 0 <= probOfZero <= 1, and produces a Bernoulli variate,
// which is always consistent between distributed nodes
std::uniform_real_distribution<qreal> distrib(0, 1); // ~[0,1]
// advances generator on every node, retaining consensus
qreal sample = distrib(mainGenerator);
// produces 0 with probOfZero probability
return sample > probOfZero;
}
qindex rand_getRandomMultiQubitOutcome(vector<qreal> probs) {
// assumes sum(probs) = 1, and produces a multinomial variate
// which is always consistent between distributed nodes
std::uniform_real_distribution<qreal> distrib(0, 1); // ~[0,1]
// advances generator on every node, retaining consensus
qreal sample = distrib(mainGenerator);
// map sample to an element of probs
qreal cumProb = 0;
for (size_t i=0; i<probs.size(); i++) {
cumProb += probs[i];
if (sample < cumProb)
return i;
}
// it is principally possible that cumProb == 1 - eps, and that
// sample lies within [1-eps, 1], and should take final elem
if (1 - cumProb <= validateconfig_getEpsilon())
return probs.size() - 1;
error_randomiserGivenNonNormalisedProbList();
return probs.size();
}
/*
* STATE AMPLITUDE SAMPLING
*/
unsigned rand_getThreadSharedRandomSeed(bool distinctPerNode) {
// (callable by multiple nodes, but NOT by multiple threads!)
// this function produces a seed which can be subsequently
// used by many threads (each perturbing their seed via their
// thread rank) to generate random amplitudes in parallel.
// The dispatched seed is informed by the mainGenerator,
// such that the user's API seeding determines both all
// measurement outcomes and state amps, whilst retaining
// independence amps for each subsequent random state
// a single uniform seed suffices to seed local random amp generation
unsigned maxSeed = std::numeric_limits<unsigned>::max();
std::uniform_int_distribution<unsigned> distrib(0, maxSeed); // ~[0 .. max]
// if we want the same seed on every node, advance all generators
if (!distinctPerNode)
return distrib(mainGenerator);
// otherwise, if we wish for distinct per-node seeds (e.g. a
// Qureg is distributed in a distributed environment)...
unsigned mySeed = 0;
int myRank = comm_getRank();
int numNodes = comm_getNumNodes();
// then we must advance all generators #ranks times...
for (int rank=0; rank<numNodes; rank++) {
unsigned globalSeed = distrib(mainGenerator);
// but keep a distinct seed per-node
if (rank == myRank)
mySeed = globalSeed;
}
return mySeed;
}
std::mt19937_64 rand_getThreadPrivateGenerator(unsigned sharedSeed, int threadId) {
// combine the shared seed (same per-thread, potentially per-node)
// with the thread ID so that thread RNG outcomes differ
std::seed_seq seeds { sharedSeed, static_cast<unsigned>(threadId) };
// give each thread an independent generator, for thread safety
std::mt19937_64 threadGenerator;
threadGenerator.seed(seeds);
return threadGenerator;
}
std::normal_distribution<qreal> rand_getThreadPrivateAmpAbsDistribution() {
// there's nothing special about our instantiation that
// makes it thread-specific; the name of this function
// reminds the user to instantiate one distribution
// per-thread just to avoid inefficient re-instantiation
// per iteration of a hot-loop
return std::normal_distribution<qreal>(0, 1); // mean=0, var=1
}
std::uniform_real_distribution<qreal> rand_getThreadPrivateAmpPhaseDistribution() {
// there's nothing special about our instantiation that
// makes it thread-specific; the name of this function
// reminds the user to instantiate one distribution
// per-thread just to avoid inefficient re-instantiation
// per iteration of a hot-loop
return std::uniform_real_distribution<qreal>(0, 2*const_PI);
}
qcomp rand_getThreadPrivateRandomAmp(std::mt19937_64 &gen, std::normal_distribution<qreal> &normDist, std::uniform_real_distribution<qreal> &phaseDist) {
// generate the amp's probability (unnormalised)
qreal n1 = normDist(gen);
qreal n2 = normDist(gen);
qreal prob = n1*n1 + n2*n2;
// generate the amp's complex phase
qreal phase = phaseDist(gen);
// produce an unnormalised amp; subsequent normalisation
// (divising by all probs between all nodes) will make
// prob a chi-squared variate, and amp uniformly random.
// https://sumeetkhatri.com/wp-content/uploads/2020/05/random_pure_states.pdf
qcomp amp = std::sqrt(prob) * std::exp(phase * 1_i);
return amp;
}