-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathlocaliser.cpp
More file actions
2316 lines (1654 loc) · 88.4 KB
/
localiser.cpp
File metadata and controls
2316 lines (1654 loc) · 88.4 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @file
* Internal functions which localize the data needed for simulation.
* That is, they determine whether performing a simulation requires
* Qureg amplitudes from other distributed nodes and if so, invoke
* the necessary communication, before finally calling the
* embarrassingly parallel subroutines in accelerator.cpp. This is
* done agnostically of whether amplitudes of the Qureg are being
* stored in RAM (CPU) or VRAM (GPU). The bespoke per-operator logic
* herein is what makes QuEST v4 truly unique among simulators!
*
* @author Tyson Jones
*/
#include "quest/include/qureg.h"
#include "quest/include/paulis.h"
#include "quest/include/matrices.h"
#include "quest/include/initialisations.h"
#include "quest/src/core/errors.hpp"
#include "quest/src/core/bitwise.hpp"
#include "quest/src/core/utilities.hpp"
#include "quest/src/core/localiser.hpp"
#include "quest/src/core/accelerator.hpp"
#include "quest/src/comm/comm_config.hpp"
#include "quest/src/comm/comm_routines.hpp"
#include "quest/src/cpu/cpu_config.hpp"
#include "quest/src/gpu/gpu_config.hpp"
#include <tuple>
#include <array>
#include <vector>
#include <complex>
#include <algorithm>
#include <unordered_map>
using std::vector;
using std::tuple;
/*
* PRIVATE FUNCTIONS
*/
void assertValidCtrlStates(vector<int> ctrls, vector<int> ctrlStates) {
// providing no control states is always valid (to invoke default all-on-1)
if (ctrlStates.empty())
return;
// otherwise a state must be explicitly given for each ctrl
if (ctrlStates.size() != ctrls.size())
error_localiserNumCtrlStatesInconsistentWithNumCtrls();
}
void setDefaultCtrlStates(vector<int> ctrls, vector<int> &states) {
// no states necessary if there are no control qubits
if (ctrls.empty())
return;
// default ctrl state is all-1
if (states.empty())
states.insert(states.end(), ctrls.size(), 1);
}
bool doesGateRequireComm(Qureg qureg, vector<int> targs) {
// non-distributed quregs never communicate (duh)
if (!qureg.isDistributed)
return false;
// communication necessary when any prefix qubit is targeted
return ! util_areAllQubitsInSuffix(targs, qureg);
}
bool doesGateRequireComm(Qureg qureg, int targ) {
return doesGateRequireComm(qureg, vector{targ});
}
bool doesChannelRequireComm(Qureg qureg, vector<int> ketQubits) {
if (!qureg.isDensityMatrix)
error_localiserPassedStateVecToChannelComCheck();
// ket-qubits are gauranteed to be in the suffix (because we distributed >=1 column per node),
// so channels invoke communication if any corresponding bra-qubits are in prefix
auto braQubits = util_getBraQubits(ketQubits, qureg);
return doesGateRequireComm(qureg, braQubits);
}
bool doesChannelRequireComm(Qureg qureg, int ketQubit) {
return doesChannelRequireComm(qureg, vector{ketQubit});
}
bool doAnyLocalStatesHaveQubitValues(Qureg qureg, vector<int> qubits, vector<int> states) {
// this answers the generic question of "do any of the given qubits lie in the
// prefix substate with node-fixed values inconsistent with the given states?"
// non-distributed quregs always have amps satisfying ctrls
if (!qureg.isDistributed)
return true;
// check each ctrl qubit
for (size_t i=0; i<qubits.size(); i++) {
// consider only ctrls which operate on the prefix substate
if (util_isQubitInSuffix(qubits[i], qureg))
continue;
// abort if any prefix ctrl has wrong bit value
if (util_getRankBitOfQubit(qubits[i], qureg) != states[i])
return false;
}
// otherwise all prefix qubits have the specified values
return true;
}
void removePrefixQubitsAndStates(Qureg qureg, vector<int> &qubits, vector<int> &states) {
vector<int> suffixQubits(0); suffixQubits.reserve(qubits.size());
vector<int> suffixStates(0); suffixStates.reserve(states.size());
// collect suffix qubits/states
for (size_t i=0; i<qubits.size(); i++)
if (util_isQubitInSuffix(qubits[i], qureg)) {
suffixQubits.push_back(qubits[i]);
suffixStates.push_back(states[i]);
}
// overwrite given vectors
qubits = suffixQubits;
states = suffixStates;
}
auto getCtrlsAndTargsSwappedToMinSuffix(Qureg qureg, vector<int> ctrls, vector<int> targs) {
// this function is called by multi-target dense matrix, and is used to find
// targets in the prefix substate and where they can be swapped into the suffix
// to enable subsequent embarrassingly parallel simulation. Note we seek the MIN
// available indices in the suffix, since this minimises the stride of the local
// simulation, improving caching performance.
// nothing to do if all targs are already in suffix
if (!doesGateRequireComm(qureg, targs))
return tuple{ctrls, targs};
// prepare masks to avoid quadratic nested looping
qindex targMask = getBitMask(targs.data(), targs.size());
qindex ctrlMask = getBitMask(ctrls.data(), ctrls.size());
int minNonTarg = getIndOfNextRightmostZeroBit(targMask, -1);
// prepare map from control qubit to its index in ctrls list (i.e. inverse of ctrls)
std::unordered_map<int,int> ctrlInds;
for (size_t i=0; i<ctrls.size(); i++)
ctrlInds[ctrls[i]] = i;
// check every target in arbitrary order, modifying our copies of targs and ctrls as we go
for (size_t i=0; i<targs.size(); i++) {
int targ = targs[i];
// consider only targs in the prefix substate
if (util_isQubitInSuffix(targ, qureg))
continue;
// we will swap targ with minNonTarg, but must first move that it of ctrls
if (getBit(ctrlMask, minNonTarg) == 1) {
// find and swap that ctrl with the old targ
int ctrlInd = ctrlInds[minNonTarg];
ctrls[ctrlInd] = targ;
// update our ctrl trackers
ctrlInds[targ] = ctrlInd;
ctrlInds[minNonTarg] = -1; // erases minNonTarg (for clarity)
ctrlMask = flipTwoBits(ctrlMask, minNonTarg, targ);
}
// swap the prefix targ with the smallest available suffix targ
targs[i] = minNonTarg;
// update our targ trackers
targMask = flipTwoBits(targMask, targ, minNonTarg);
minNonTarg = getIndOfNextRightmostZeroBit(targMask, minNonTarg);
}
// the ordering in ctrls relative to the caller's ctrlStates is unchanged
return tuple{ctrls, targs};
}
auto getQubitsSwappedToMaxSuffix(Qureg qureg, vector<int> qubits) {
// this function is called by any-targ partial trace, and is used to find
// targets in the prefix substate and where they can be swapped into the suffix
// to enable subsequent embarrassingly parallel simulation. Note we seek the MAX
// available indices in the suffix, since this heuristically reduces the
// disordering of the surviving qubits after the trace, reducing the number of
// subsequent order-restoring SWAPs
// nothing to do if all qubits are already in suffix
if (!doesGateRequireComm(qureg, qubits))
return qubits;
// prepare mask to avoid quadratic nested looping
qindex qubitMask = getBitMask(qubits.data(), qubits.size());
int maxFreeSuffixQubit = getIndOfNextLeftmostZeroBit(qubitMask, qureg.logNumAmpsPerNode);
// enumerate qubits backward, modifying our copy of qubits as we go
for (size_t i=qubits.size(); i-- != 0; ) {
int qubit = qubits[i];
// consider only qubits in the prefix substate
if (util_isQubitInSuffix(qubit, qureg))
continue;
// swap the prefix qubit into the largest available suffix position
qubits[i] = maxFreeSuffixQubit;
// update trackers
qubitMask = flipTwoBits(qubitMask, qubit, maxFreeSuffixQubit);
maxFreeSuffixQubit = getIndOfNextLeftmostZeroBit(qubitMask, maxFreeSuffixQubit);
}
// return our modified copy
return qubits;
}
auto getNonSwappedCtrlsAndStates(vector<int> oldCtrls, vector<int> oldStates, vector<int> newCtrls) {
vector<int> sameCtrls(0); sameCtrls .reserve(oldCtrls.size());
vector<int> sameStates(0); sameStates.reserve(oldStates.size());
for (size_t i=0; i<oldCtrls.size(); i++)
if (oldCtrls[i] == newCtrls[i]) {
sameCtrls .push_back(oldCtrls[i]);
sameStates.push_back(oldStates[i]);
}
return tuple{sameCtrls, sameStates};
}
/*
* PRIVATE SPOOFERS
*/
extern Qureg qureg_populateNonHeapFields(int numQubits, int isDensMatr, int useDistrib, int useGpuAccel, int useMultithread);
Qureg getSpoofedDistributedBufferlessQuregFromLocalQureg(Qureg local, Qureg distrib) {
assert_localiserDistribQuregSpooferGivenValidQuregs(local, distrib);
// this function makes a new Qureg, leveraging 'local's existing
// memory, which has the same distribution as the given distributed Qureg.
// critically however, the new Qureg will lack communication buffers, so
// must only be called by embarrassingly parallel routines!
// overwrite spoof's fields with distrib's, setting correct dimensions
Qureg spoof = distrib;
// set spoof's pointers to a rank-specific offset of local's
qindex offset = util_getGlobalIndexOfFirstLocalAmp(distrib);
spoof.cpuAmps = &local.cpuAmps[offset];
spoof.gpuAmps = (local.isGpuAccelerated)? &local.gpuAmps[offset] : local.gpuAmps;
// pedantically unbind distrib's communication buffers
spoof.cpuCommBuffer = nullptr;
spoof.gpuCommBuffer = nullptr;
return spoof;
}
FullStateDiagMatr getSpoofedDistributedMatrFromDistributedQureg(FullStateDiagMatr local, Qureg distrib) {
// this function makes a new FullStateDiagMatr, leveraging 'local's existing
// memory, which has the same distribution as the given distributed Qureg.
// inherit all fields of local, subsequently overwriting those related to distribution
FullStateDiagMatr spoof = local;
spoof.isDistributed = 1;
spoof.isMultithreaded = local.isMultithreaded; // safely ignored
spoof.numElemsPerNode = local.numElems / distrib.numNodes; // divides evenly
// offset pointers to local's existing memory, avoiding de-referencing nullptr (illegal)
qindex offset = (distrib.isDensityMatrix)?
util_getGlobalColumnOfFirstLocalAmp(distrib):
util_getGlobalIndexOfFirstLocalAmp(distrib);
spoof.cpuElems = &local.cpuElems[offset];
spoof.gpuElems = (local.isGpuAccelerated)? &local.gpuElems[offset] : local.gpuElems;
return spoof;
}
Qureg getSpoofedBufferlessQuregFromFullStateDiagMatr(FullStateDiagMatr matr) {
// this function makes a new Qureg, leveraging the FullStateDiagMatr's
// existing memory, with the same properties and memory layout. This
// enables re-use of backend statevec functions for processing matrices.
bool isDensMatr = false;
Qureg qureg = qureg_populateNonHeapFields(
matr.numQubits, isDensMatr,
matr.isDistributed, matr.isGpuAccelerated, matr.isMultithreaded);
// bind matr's existing CPU and GPU memory to Qureg
qureg.cpuAmps = matr.cpuElems;
qureg.gpuAmps = matr.gpuElems;
// comm-buffers remain null which may be inconsistent with its distributed
// status and would ergo fail validation; that's fine for our internal use
// which never makes use of the communication buffers
return qureg;
}
Qureg getSpoofedSerialStateVecFromDensMatrAndAmps(Qureg denseQureg, qcomp* amps) {
// imitate statevector, turn off all parallelisation
int isDensMatr = 0;
int useDistrib = 0;
int useGpuAccel = 0;
int useMultithread = 0;
Qureg spoof = qureg_populateNonHeapFields(
denseQureg.numQubits, isDensMatr,
useDistrib, useGpuAccel, useMultithread);
// bind the external memory
spoof.cpuAmps = amps;
return spoof;
}
auto getSpoofedQuregAndMatrWithMatchingDistributions(Qureg qureg, FullStateDiagMatr matr) {
// in defensive design, this function modifies only new structs rather than
// the passed structs, in case the latter are later changed to references
// when only matr is local, spoof it to be distributed
if (qureg.isDistributed && !matr.isDistributed) {
FullStateDiagMatr matrSpoof = getSpoofedDistributedMatrFromDistributedQureg(matr, qureg);
return tuple{qureg,matrSpoof};
}
// when only qureg is local, spoof it to be distributed
if (!qureg.isDistributed && matr.isDistributed) {
Qureg quregSpoof = qureg_populateNonHeapFields(
qureg.numQubits, qureg.isDensityMatrix,
matr.isDistributed, // becomes distributed
qureg.isGpuAccelerated,
matr.isMultithreaded); // consults matr's multithreading (appropriate for reduced size)
quregSpoof = getSpoofedDistributedBufferlessQuregFromLocalQureg(qureg, quregSpoof);
return tuple{quregSpoof,matr};
}
// when distributions agree, return originals
return tuple{qureg,matr};
}
Qureg getSpoofedLocalStateVecFromDistributedDensMatrBuffers(Qureg densmatr) {
assert_localiserGivenDensMatr(densmatr);
bool isDensMatr = false;
bool useDistrib = false;
bool useMultithr = densmatr.isMultithreaded; // unnecessary
bool useGpuAccel = densmatr.isGpuAccelerated; // necessary
Qureg spoof = qureg_populateNonHeapFields(densmatr.numQubits, isDensMatr, useDistrib, useGpuAccel, useMultithr);
// both are none if densmatr is not distributed (handled by caller)
spoof.cpuAmps = densmatr.cpuCommBuffer;
spoof.gpuAmps = densmatr.gpuCommBuffer; // may be null
return spoof;
}
Qureg createSpoofedLocalStateVecFromDensMatr(Qureg densmatr, bool &memWasAlloc) {
assert_localiserGivenDensMatr(densmatr);
// this function spoofs a non-distributed statevector Qureg with the
// same number of qubits as the given densmatr. It uses densmatr's
// mutlithread and GPU status, and if they exist, re-uses densmatr's
// CPU and GPU communication buffers for its main memory. If densmatr
// has no communication buffers, temporary memory is created, which is
// acceptable since it is expected much smaller than densmatr's local
// memory (a factor densmatr.numColsPerNode). In that scenario,
// memWasAlloc is overwritten to be true.
memWasAlloc = false;
Qureg spoof = getSpoofedLocalStateVecFromDistributedDensMatrBuffers(densmatr);
// if it exists, we repurpose densmatr's existing buffer space to store
// pure's statevector, since every node contains >=1 columns; it can fit!
if (densmatr.isDistributed)
return spoof;
// otherwise, we must create temporary memory for pure. Even if we need only
// create GPU memory, we create the matching CPU memory too for defensive design
memWasAlloc = true;
spoof.cpuAmps = cpu_allocArray(spoof.numAmps);
assert_localiserSuccessfullyAllocatedTempMemory(spoof.cpuAmps, false); // CPU
if (spoof.isGpuAccelerated) {
spoof.gpuAmps = gpu_allocArray(spoof.numAmps);
assert_localiserSuccessfullyAllocatedTempMemory(spoof.gpuAmps, true); // GPU
}
return spoof;
}
void freeSpoofedLocalStateVec(Qureg spoof, bool wasMemAlloc) {
if (!wasMemAlloc)
return;
cpu_deallocArray(spoof.cpuAmps);
if (spoof.isGpuAccelerated)
gpu_deallocArray(spoof.gpuAmps);
}
/*
* COMMUNICATION WRAPPERS
*/
void exchangeAmpsToBuffersWhereQubitsAreInStates(Qureg qureg, int pairRank, vector<int> qubits, vector<int> states) {
// when there are no constraining qubits, all amps are exchanged; there is no need to pack the buffer.
// this is typically triggered when a communicating localiser function is given no control qubits
if (qubits.empty()) {
comm_exchangeAmpsToBuffers(qureg, pairRank);
return;
}
// otherwise, we pack and exchange only to-be-communicated amps between sub-buffers
qindex numPacked = accel_statevec_packAmpsIntoBuffer(qureg, qubits, states);
comm_exchangeSubBuffers(qureg, numPacked, pairRank);
}
/*
* GETTERS
*/
qcomp localiser_statevec_getAmp(Qureg qureg, qindex globalInd) {
// this custom routine exists, in lieu of merely invoking
// getAmps() below, because it avoids the superfluous rank
// enumeration and is therefore locally faster; there
// may be applications where this is desirable (maybe)
// when qureg not distributed (although env may be), every
// node returns their identical local amp
if (!qureg.isDistributed) {
qcomp amp;
accel_statevec_getAmps_sub(&, qureg, globalInd, 1);
return amp;
}
// otherwise one node contains the target amp
qcomp amp = 0;
int sender = util_getRankContainingIndex(qureg, globalInd);
if (sender == qureg.rank) {
qindex localInd = util_getLocalIndexOfGlobalIndex(qureg, globalInd);
accel_statevec_getAmps_sub(&, qureg, localInd, 1);
}
// which it shares with all other nodes
comm_broadcastAmp(sender, &);
return amp;
}
void localiser_statevec_getAmps(qcomp* outAmps, Qureg qureg, qindex globalStartInd, qindex globalNumAmps) {
// we do not assert state-vec, since the density matrix routine re-uses this function
// when not distributed, all nodes merely perform direct local overwrite and finish
if (!qureg.isDistributed) {
accel_statevec_getAmps_sub(outAmps, qureg, globalStartInd, globalNumAmps);
return;
}
// when distributed, each node will broadcast their overlap (which may be zero) with the global range
int myRank = comm_getRank();
int numNodes = comm_getNumNodes();
// which they first overwrite into their local copies of out (may involve a GPU-to-CPU copy)
if (util_areAnyVectorElemsWithinNode(myRank, qureg.numAmpsPerNode, globalStartInd, globalNumAmps)) {
auto localInds = util_getLocalIndRangeOfVectorElemsWithinNode(myRank, qureg.numAmpsPerNode, globalStartInd, globalNumAmps);
accel_statevec_getAmps_sub(&outAmps[localInds.localDuplicStartInd], qureg, localInds.localDistribStartInd, localInds.numElems);
}
// determine the overlap with each node (i.e. which amps, if any, they contribute)
vector<qindex> globalRecvInds(numNodes);
vector<qindex> localSendInds (numNodes);
vector<qindex> numAmpsPerRank(numNodes, 0); // default = zero contributed amps
for (int sendRank=0; sendRank<numNodes; sendRank++) {
if (!util_areAnyVectorElemsWithinNode(sendRank, qureg.numAmpsPerNode, globalStartInd, globalNumAmps))
continue;
auto inds = util_getLocalIndRangeOfVectorElemsWithinNode(sendRank, qureg.numAmpsPerNode, globalStartInd, globalNumAmps);
globalRecvInds[sendRank] = inds.localDuplicStartInd;
localSendInds [sendRank] = inds.localDistribStartInd;
numAmpsPerRank[sendRank] = inds.numElems;
}
// contributor nodes broadcast, all nodes receive, so that every node populates 'outAmps' fully
comm_combineSubArrays(outAmps, globalRecvInds, localSendInds, numAmpsPerRank);
}
void localiser_densmatr_getAmps(qcomp** outAmps, Qureg qureg, qindex startRow, qindex startCol, qindex numRows, qindex numCols) {
assert_localiserGivenDensMatr(qureg);
/// @todo improve the performance!
/// this function simply serially invokes localiser_statevec_getAmps() upon
/// every indicated column, for simplicity, and since we believe this function
/// will only ever be called upon tractably small sub-matrices. After all, the
/// user is likely to serially process outAmps themselves. Our method incurs the
/// below insignificant performance penalties:
/// - we must allocate temporary memory that is the same size as outAmps,
/// but transposed, because we cannot make a pointer to a column of outAmps
/// in order to invoke localiser_statevec_getAmps() thereupon. Thereafter, we
/// serially populate outAmps with the transposed temp memory.
/// - every invocation of localiser_statevec_getAmps() invokes synchronous
/// GPU-CPU copying (a total of #numCols), whereas a bespoke implementation
/// could perform each non-contiguous copy asynchronously then wait
/// - every invocation invokes synchronous MPI broadcasting, whereas a bespoke
/// method could asynch all per-col broadcasts before a final wait
/// A custom function to remedy these issues is complicated; it would involve
/// e.g. exposing MPI_Request outside of comm_routines.cpp (unacceptable for
/// compiler compatibility), or having comm_routines cache un-fulfilled asynch
/// requests, etc.
vector<vector<qcomp>> tempOut;
util_tryAllocMatrix(tempOut, numCols, numRows, error_localiserFailedToAllocTempMemory); // transposed dim of outAmps
for (qindex c=0; c<numCols; c++) {
qindex flatInd = util_getGlobalFlatIndex(qureg, startRow, startCol + c);
localiser_statevec_getAmps(tempOut[c].data(), qureg, flatInd, numRows);
}
// serially overwrite outAmps = transpose(tempOut)
for (qindex r=0; r<numRows; r++)
for (qindex c=0; c<numCols; c++)
outAmps[r][c] = tempOut[c][r]; // writes contiguous, reads strided
}
void localiser_fullstatediagmatr_getElems(qcomp* outElems, FullStateDiagMatr matr, qindex globalStartInd, qindex globalNumElems) {
// re-use identical logic of statevector setter
Qureg qureg = getSpoofedBufferlessQuregFromFullStateDiagMatr(matr);
localiser_statevec_getAmps(outElems, qureg, globalStartInd, globalNumElems);
}
/*
* SETTERS
*/
void localiser_statevec_setAmps(qcomp* inAmps, Qureg qureg, qindex globalStartInd, qindex globalNumAmps) {
// we do not assert Qureg is a state-vector, since the
// density matrix routine leverages this function
// always embarrassingly parallel, since inAmps is duplicated on every node;
// nodes simply determine which amps overlap their partition, and use them
if (!qureg.isDistributed) {
accel_statevec_setAmps_sub(inAmps, qureg, globalStartInd, globalNumAmps);
return;
}
if (!util_areAnyVectorElemsWithinNode(qureg.rank, qureg.numAmpsPerNode, globalStartInd, globalNumAmps))
return;
auto range = util_getLocalIndRangeOfVectorElemsWithinNode(qureg.rank, qureg.numAmpsPerNode, globalStartInd, globalNumAmps);
accel_statevec_setAmps_sub(&inAmps[range.localDuplicStartInd], qureg, range.localDistribStartInd, range.numElems);
}
void localiser_densmatr_setAmps(qcomp** inAmps, Qureg qureg, qindex startRow, qindex startCol, qindex numRows, qindex numCols) {
assert_localiserGivenDensMatr(qureg);
/// @todo improve the performance!
/// this function works by simply enumerating each column of inAmps
/// (which requires explicit preparation, because inAmps is passed
/// column-wise, rather than row-wise), passing each to the above
/// statevec routine. It is ergo similar to the naive method used by
/// localiser_densmatr_getAmps(), though is embarrassingly parallel.
/// This func allocates temporary memory as large as numRows*numCols
/// (which could be an entire Qureg's worth), and serially computes
/// the transpose (which can be as bad as serial iteration of the
/// whole qureg). This is grossly inefficient, and worse than merely
/// parallel-overwriting CPU memory then copying to GPU.
vector<vector<qcomp>> tempAmps;
util_tryAllocMatrix(tempAmps, numCols, numRows, error_localiserFailedToAllocTempMemory); // transpose of inAmps
// serially overwrite tempAmps = transpose(inAmps)
for (qindex c=0; c<numCols; c++)
for (qindex r=0; r<numRows; r++)
tempAmps[c][r] = inAmps[r][c]; // writes contiguous, reads strided
// call the statevector function upon each column
for (qindex c=0; c<numCols; c++) {
qindex flatInd = util_getGlobalFlatIndex(qureg, startRow, startCol + c);
localiser_statevec_setAmps(tempAmps[c].data(), qureg, flatInd, numRows);
}
}
void localiser_densmatr_setAmpsToPauliStrSum(Qureg qureg, PauliStrSum sum) {
assert_localiserGivenDensMatr(qureg);
// always embarrassingly parallel
accel_densmatr_setAmpsToPauliStrSum_sub(qureg, sum);
}
void localiser_fullstatediagmatr_setElems(FullStateDiagMatr matr, qindex startInd, qcomp* in, qindex numElems) {
// modification of a FullStateDiagMatr is identical to that of a
// statevector Qureg, so we spoof an identically-deployed Qureg
Qureg spoof = getSpoofedBufferlessQuregFromFullStateDiagMatr(matr);
// invoke the Qureg setter, which will modify matr's memory
localiser_statevec_setAmps(in, spoof, startInd, numElems);
// note that FullStateDiagMatr needs its CPU and GPU memories
// to always be consistent with one another (like all matrix
// types), since this is a precondition assumed by accelerator.cpp.
// So if the above function modified GPU mem, we also trigger CPU.
if (spoof.isGpuAccelerated) {
spoof.isGpuAccelerated = 0;
localiser_statevec_setAmps(in, spoof, startInd, numElems);
}
}
void localiser_fullstatediagmatr_setElemsToPauliStrSum(FullStateDiagMatr out, PauliStrSum in) {
// always embarrassingly parallel. Note that accelerator will
// safely keep CPU and GPU memory of FullStateDiagMatr consistent
accel_fullstatediagmatr_setElemsToPauliStrSum(out, in);
}
/*
* STATE INITIALISATION
*/
// defined later in this file, but repurposed here for density matrix initialisation
void mixDensityMatrixWithStatevector(qreal outProb, Qureg out, qreal inProb, Qureg in);
void localiser_statevec_initArbitraryPureState(Qureg qureg, qcomp* amps) {
assert_localiserGivenStateVec(qureg);
// always embarrassingly parallel, and merely invokes local copying
qindex startInd = 0;
localiser_statevec_setAmps(amps, qureg, startInd, qureg.numAmps);
}
void localiser_densmatr_initArbitraryPureState(Qureg qureg, qcomp* amps) {
assert_localiserGivenDensMatr(qureg);
// we cannot simply call a copy routine like the statevector case,
// because amps will not be contiguously located in the density matrix.
// Instead, we spoof a local CPU-only statevector, and bind amps to it
Qureg spoof = getSpoofedSerialStateVecFromDensMatrAndAmps(qureg, amps);
localiser_densmatr_initPureState(qureg, spoof);
}
void localiser_densmatr_initArbitraryMixedState(Qureg qureg, qcomp** amps) {
/// @todo
/// the current invoked implementation of setAmps() is extraordinarily
/// inefficient in the full-Qureg regime. Fix setAmps(), then update this!
qindex startRow = 0;
qindex startCol = 0;
qindex numRows = powerOf2(qureg.numQubits);
qindex numCols = numRows;
localiser_densmatr_setAmps(amps, qureg, startRow, startCol, numRows, numCols);
}
void localiser_statevec_initUniformState(Qureg qureg, qcomp amp) {
// always embarrassingly parallel
accel_statevec_initUniformState_sub(qureg, amp);
}
void localiser_statevec_initDebugState(Qureg qureg) {
// always embarrassingly parallel
accel_statevec_initDebugState_sub(qureg);
}
void localiser_statevec_initClassicalState(Qureg qureg, qindex globalInd) {
// all nodes clear all amps
accel_statevec_initUniformState_sub(qureg, 0);
// one node (or all if qureg not distributed) modifies 1 amp
qcomp amp = 1;
localiser_statevec_setAmps(&, qureg, globalInd, 1);
}
void localiser_densmatr_initPureState(Qureg qureg, Qureg pure) {
assert_localiserGivenDensMatr(qureg);
assert_localiserGivenStateVec(pure);
// we sneakily re-use the above mixing functions, since the
// superfluous flops (multiplication of existing qureg amps
// with zero) are completely eclipsed by the memory move costs.
// note however we forego the chance to perform some minor
// numerical optimisations, like setting the diagonals to
// strictly real (true regardless of qureg normalisation)
qreal quregProb = 0;
qreal pureProb = 1;
mixDensityMatrixWithStatevector(quregProb, qureg, pureProb, pure);
}
void localiser_statevec_initUnnormalisedUniformlyRandomPureStateAmps(Qureg qureg) {
assert_localiserGivenStateVec(qureg);
// generation of unnormalised states is embarrassingly parallel;
// subsequent normalisation will require reduction/communication
accel_statevec_initUnnormalisedUniformlyRandomPureStateAmps_sub(qureg);
}
void localiser_densmatr_initUniformlyRandomPureStateAmps(Qureg qureg) {
assert_localiserGivenDensMatr(qureg);
// we require a random, normalised statevector, duplicated on every
// node, from which to initialise the density-matrix. We obtain this
// by first spoofing a new non-distributed pure state, re-using qureg's
// communication buffers if they exist, else creating temp memory
bool wasMemAlloc = false;
Qureg pure = createSpoofedLocalStateVecFromDensMatr(qureg, wasMemAlloc); // overwrites wasMemAlloc
// initialise the spoofed pure Qureg to a normalised, uniformly random
// statevector; this is calling the same API function which invoked THIS
// very function, but instead passing a statevector
initRandomPureState(pure); // harmlessly re-valdates
// then, we simply initialise the density matrix in this pure state.
// Note that initPureState() calls mixDensityMatrixWithStatevector()
// which writes to qureg's communication buffer only when the pure
// qureg is distributed; we safely avoid that scenario, which would
// conflict with our hijacking of qureg's buffer when allocated.
localiser_densmatr_initPureState(qureg, pure);
// if we allocated temporary memory, free it
freeSpoofedLocalStateVec(pure, wasMemAlloc);
}
void localiser_densmatr_initMixtureOfUniformlyRandomPureStates(Qureg qureg, qindex numPureStates) {
assert_localiserGivenDensMatr(qureg);
// this function merely generates a random pure state, uniformly
// mixes it into qureg (initially blank), and sequentially
// repeats this process, increasingly mixing qureg.
initBlankState(qureg);
// spoof a statevector Qureg we can rnadomise, re-using
// qureg's communication buffer memory if possible, else
// creating temporary memory we must later free
bool wasMemAlloc = false;
Qureg pure = createSpoofedLocalStateVecFromDensMatr(qureg, wasMemAlloc); // overwrites wasMemAlloc
// create mixture qureg = sum_n^N (1/N) pure_n
for (qindex n=0; n<numPureStates; n++) {
initRandomPureState(pure);
mixDensityMatrixWithStatevector(1, qureg, 1./numPureStates, pure);
}
// for large numPureStates, the above process is likely to
// be numerically imprecise, so we finally renormalise
setQuregToRenormalized(qureg);
// free any allocated temp memory
freeSpoofedLocalStateVec(pure, wasMemAlloc);
}
/*
* SWAP
*/
void anyCtrlSwapBetweenPrefixAndPrefix(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, int targ1, int targ2) {
int prefInd1 = util_getPrefixInd(targ1, qureg);
int prefInd2 = util_getPrefixInd(targ2, qureg);
// half of all nodes contain no to-be-swapped amps and immediately finish
if (getBit(qureg.rank, prefInd1) == getBit(qureg.rank, prefInd2))
return;
// but the remaining half exchange the entirety of their amps which are in the ctrl states
int pairRank = flipTwoBits(qureg.rank, prefInd1, prefInd2);
exchangeAmpsToBuffersWhereQubitsAreInStates(qureg, pairRank, ctrls, ctrlStates);
// and use them to overwrite their local amps satisfying ctrl states, then finish
accel_statevec_anyCtrlSwap_subB(qureg, ctrls, ctrlStates);
}
void anyCtrlSwapBetweenPrefixAndSuffix(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, int suffixTarg, int prefixTarg) {
// every node exchanges at most half its amps; those where suffixTarg bit differs from rank's fixed prefixTarg bit
int pairRank = util_getRankWithQubitFlipped(prefixTarg, qureg);
int suffixState = ! util_getRankBitOfQubit(prefixTarg, qureg);
// pack and exchange only to-be-communicated amps between sub-buffers
vector<int> qubits = ctrls;
vector<int> states = ctrlStates;
qubits.push_back(suffixTarg);
states.push_back(suffixState);
exchangeAmpsToBuffersWhereQubitsAreInStates(qureg, pairRank, qubits, states);
// we use the recevied buffer amplitudes to modify half of the local bits which satisfy ctrls
accel_statevec_anyCtrlSwap_subC(qureg, ctrls, ctrlStates, suffixTarg, suffixState);
}
void localiser_statevec_anyCtrlSwap(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, int targ1, int targ2) {
assertValidCtrlStates(ctrls, ctrlStates);
setDefaultCtrlStates(ctrls, ctrlStates);
// ensure targ2 > targ1
if (targ1 > targ2)
std::swap(targ1, targ2);
// node has nothing to do if all local amps violate control condition
if (!doAnyLocalStatesHaveQubitValues(qureg, ctrls, ctrlStates))
return;
// retain only suffix control qubits as relevant to communication and local amp modification
removePrefixQubitsAndStates(qureg, ctrls, ctrlStates);
// determine necessary communication
bool comm1 = doesGateRequireComm(qureg, targ1);
bool comm2 = doesGateRequireComm(qureg, targ2);
if (comm2 && comm1)
anyCtrlSwapBetweenPrefixAndPrefix(qureg, ctrls, ctrlStates, targ1, targ2);
if (comm2 && !comm1)
anyCtrlSwapBetweenPrefixAndSuffix(qureg, ctrls, ctrlStates, targ1, targ2);
if (!comm2 && !comm1)
accel_statevec_anyCtrlSwap_subA(qureg, ctrls, ctrlStates, targ1, targ2);
}
/*
* MULTI-SWAP
*/
void anyCtrlMultiSwapBetweenPrefixAndSuffix(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, vector<int> targsA, vector<int> targsB) {
// this is an internal function called by the below routines which require
// performing a sequence of SWAPs to reorder qubits, or move them into suffix.
// the SWAPs act on unique qubit pairs and so commute.
/// @todo
/// - the sequence of pair-wise full-swaps should be more efficient as a
/// "single" sequence of smaller messages sending amps directly to their
/// final destination node. This could use a new "multiSwap" function.
/// - if the user has compiled cuQuantum, and Qureg is GPU-accelerated, the
/// multiSwap function should use custatevecSwapIndexBits() if local,
/// or custatevecDistIndexBitSwapSchedulerSetIndexBitSwaps() if distributed,
/// although the latter requires substantially more work like setting up
/// a communicator which may be inelegant alongside our own distribution scheme.
// perform necessary swaps to move all targets into suffix, each of which invokes communication
for (size_t i=0; i<targsA.size(); i++) {
if (targsA[i] == targsB[i])
continue;
int suffixTarg = std::min(targsA[i], targsB[i]);
int prefixTarg = std::max(targsA[i], targsB[i]);
anyCtrlSwapBetweenPrefixAndSuffix(qureg, ctrls, ctrlStates, suffixTarg, prefixTarg);
}
}
/*
* ONE-TARGET DENSE MATRIX
*/
void anyCtrlOneTargDenseMatrOnPrefix(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, int targ, CompMatr1 matr) {
int pairRank = util_getRankWithQubitFlipped(targ, qureg);
exchangeAmpsToBuffersWhereQubitsAreInStates(qureg, pairRank, ctrls, ctrlStates);
// extract relevant gate elements
int bit = util_getRankBitOfQubit(targ, qureg);
qcomp fac0 = matr.elems[bit][ bit];
qcomp fac1 = matr.elems[bit][!bit];
// update local amps using received amps in buffer
accel_statevec_anyCtrlOneTargDenseMatr_subB(qureg, ctrls, ctrlStates, fac0, fac1);
}
void localiser_statevec_anyCtrlOneTargDenseMatr(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, int targ, CompMatr1 matr, bool conj) {
assertValidCtrlStates(ctrls, ctrlStates);
setDefaultCtrlStates(ctrls, ctrlStates);
// node has nothing to do if all local amps violate control condition
if (!doAnyLocalStatesHaveQubitValues(qureg, ctrls, ctrlStates))
return;
// retain only suffix control qubits as relevant to communication and local amp modification
removePrefixQubitsAndStates(qureg, ctrls, ctrlStates);
if (conj)
matr = util_getConj(matr);
// perform embarrassingly parallel routine or communication-inducing swaps
doesGateRequireComm(qureg, targ)?
anyCtrlOneTargDenseMatrOnPrefix(qureg, ctrls, ctrlStates, targ, matr) :
accel_statevec_anyCtrlOneTargDenseMatr_subA(qureg, ctrls, ctrlStates, targ, matr);
}
/*
* TWO-TARGET & ANY-TARGET DENSE MATRIX
*
* which are intermixed, despite each having their own local backend
* implementations, because they use identical communication logic
*/
void anyCtrlTwoOrAnyTargDenseMatrOnSuffix(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, vector<int> targs, CompMatr2 matr, bool conj) {
if (conj) matr = util_getConj(matr);
accel_statevec_anyCtrlTwoTargDenseMatr_sub(qureg, ctrls, ctrlStates, targs[0], targs[1], matr);
}
void anyCtrlTwoOrAnyTargDenseMatrOnSuffix(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, vector<int> targs, CompMatr matr, bool conj) {
accel_statevec_anyCtrlAnyTargDenseMatr_sub(qureg, ctrls, ctrlStates, targs, matr, conj);
}
// T can be CompMatr2 or CompMatr
template <typename T>
void anyCtrlTwoOrAnyTargDenseMatr(Qureg qureg, vector<int> ctrls, vector<int> ctrlStates, vector<int> targs, T matr, bool conj) {
// node has nothing to do if all local amps violate control condition
if (!doAnyLocalStatesHaveQubitValues(qureg, ctrls, ctrlStates))