-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMPIBuffer.h
1592 lines (1445 loc) · 50.1 KB
/
MPIBuffer.h
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
//
// Kmernator/src/MPIBuffer.h
//
// Author: Rob Egan
//
/*****************
Kmernator Copyright (c) 2012, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy). All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
(1) Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
(2) Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
(3) Neither the name of the University of California, Lawrence Berkeley
National Laboratory, U.S. Dept. of Energy nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You are under no obligation whatsoever to provide any bug fixes, patches, or
upgrades to the features, functionality or performance of the source code
("Enhancements") to anyone; however, if you choose to make your Enhancements
available either publicly, or directly to Lawrence Berkeley National
Laboratory, without imposing a separate written license agreement for such
Enhancements, then you hereby grant the following license: a non-exclusive,
royalty-free perpetual license to install, use, modify, prepare derivative
works, incorporate into other computer software, distribute, and sublicense
such enhancements or derivative works thereof, in binary and source code form.
*****************/
#ifndef MPIBUFFER_H_
#define MPIBUFFER_H_
#include "config.h"
#include "Options.h"
#include "MPIBase.h"
#ifdef _USE_OPENMP
#define X_OPENMP_CRITICAL_MPI
#endif
#define _RETRY_MESSAGES false
#define _RETRY_THRESHOLD 10000
#include <vector>
// use about 32MB of memory total to batch & queue up messages between communications
// this is split up across world * thread * thread arrays
#define MPI_BUFFER_DEFAULT_SIZE (32 * 1024 * 1024)
#define MPI_MIN_TRANSMIT_DEFAULT_SIZE 2048
class _MPIOptions : public OptionsBaseInterface {
public:
_MPIOptions() : mpiBufferSize(MPI_BUFFER_DEFAULT_SIZE), mpiMinTransmitSize(MPI_MIN_TRANSMIT_DEFAULT_SIZE) {}
virtual ~_MPIOptions() {}
int &getTotalBufferSize() {
return mpiBufferSize;
}
int &getMinTransmitSize() {
return mpiMinTransmitSize;
}
void _setOptions(po::options_description &desc, po::positional_options_description &p) {
po::options_description opts("MPI Options");
opts.add_options()
("mpi-buffer-size", po::value<int>()->default_value(mpiBufferSize),
"total amount of RAM to devote to MPI message batching buffers in bytes")
("mpi-min-transmit-size", po::value<int>()->default_value(mpiMinTransmitSize), "the minimum inter rank-thread buffer size")
;
desc.add(opts);
}
bool _parseOptions(po::variables_map &vm) {
setOpt("mpi-buffer-size", mpiBufferSize);
setOpt("mpi-min-transmit-size", mpiMinTransmitSize);
return true;
}
protected:
int mpiBufferSize, mpiMinTransmitSize;
};
typedef OptionsBaseTemplate< _MPIOptions > MPIOptions;
class MPIMessageBufferBase {
public:
typedef std::pair<MPIMessageBufferBase*, int> CallbackBase;
typedef std::vector<CallbackBase> CallbackVector;
protected:
CallbackVector _flushAllCallbacks;
CallbackVector _receiveAllCallbacks;
CallbackVector _sendReceiveCallbacks;
long _deliveries;
long _numMessages;
long _sendBytes, _recvBytes;
long _syncPoints;
long _syncAttempts;
double _transitTime;
double _threadWaitingTime, _masterWaitingTime;
double _threadProcessTime, _masterProcessTime;
double _startTime;
public:
MPIMessageBufferBase() :
_deliveries(0), _numMessages(0), _sendBytes(0), _recvBytes(0), _syncPoints(0), _syncAttempts(0), _transitTime(0), _threadWaitingTime(0), _masterWaitingTime(0), _threadProcessTime(0), _masterProcessTime(0) {
_startTime = MPI_Wtime();
}
virtual ~MPIMessageBufferBase() {
LOG_VERBOSE_GATHER(2, "~MPIMessageBufferBase(): " << _deliveries
<< " deliveries, " << _numMessages << " messages, "
<< _sendBytes << " b sent, " << _recvBytes << " b recv, "
<< _syncPoints << " / " << _syncAttempts << " syncs in " << (MPI_Wtime() - _startTime)
<< " seconds (" << _transitTime << " transit, " << _threadProcessTime << " threadProcess, " << _masterProcessTime << " masterProcess, " << _threadWaitingTime << " threadWait, " << _masterWaitingTime << " masterWait)");
}
static bool isThreadSafe() {
int threadlevel;
MPI_Query_thread(&threadlevel);
return threadlevel >= MPI_THREAD_FUNNELED;
}
// receive buffers to flush before and/or during send
void addReceiveAllCallback(MPIMessageBufferBase *receiveAllBuffer) {
_receiveAllCallbacks.push_back(CallbackBase(receiveAllBuffer, -1));
receiveAll();
assert(receiveAllBuffer->getNumDeliveries() == 0);
}
void addFlushAllCallback(MPIMessageBufferBase *flushAllBuffer, int tagDest) {
_flushAllCallbacks.push_back(CallbackBase(flushAllBuffer, tagDest));
flushAll();
assert(flushAllBuffer->getNumDeliveries() == 0);
}
void addSendReceiveCallback(MPIMessageBufferBase *sendReceiveBuffer) {
_sendReceiveCallbacks.push_back(CallbackBase(sendReceiveBuffer, -1));
}
virtual long receiveAllIncomingMessages(bool untilFlushed = true) {
return 0;
}
virtual long flushAllMessageBuffers(int tagDest) {
return 0;
}
virtual long sendReceive(bool isFinalized) {
return 0;
}
long receiveAll(bool untilFlushed = true) {
long count = 0;
for (unsigned int i = 0; i < _receiveAllCallbacks.size(); i++)
count += _receiveAllCallbacks[i].first->receiveAllIncomingMessages(
untilFlushed);
LOG_DEBUG(4, "receiveAll() with " << count);
return count;
}
long flushAll() {
long count = 0;
for (unsigned int i = 0; i < _flushAllCallbacks.size(); i++)
count += _flushAllCallbacks[i].first->flushAllMessageBuffers(
_flushAllCallbacks[i].second);
LOG_DEBUG(4, "flushAll() with count " << count);
return count;
}
inline long getNumDeliveries() {
return _deliveries;
}
inline void newMessageDelivery() {
#pragma omp atomic
_deliveries++;
}
inline long getNumMessages() {
return _numMessages;
}
inline void newMessage() {
#pragma omp atomic
_numMessages++;
}
inline void syncPoint() {
#pragma omp atomic
_syncPoints++;
}
inline void syncAttempt() {
#pragma omp atomic
_syncAttempts++;
}
inline void transit(double transit) {
#pragma omp atomic
_transitTime += transit;
}
inline void threadWait(double wait) {
if (omp_get_thread_num() == 0) {
#pragma omp atomic
_masterWaitingTime += wait;
} else {
#pragma omp atomic
_threadWaitingTime += wait;
}
}
inline void threadProcess(double duration) {
if (omp_get_thread_num() == 0) {
#pragma omp atomic
_masterProcessTime += duration;
} else {
#pragma omp atomic
_threadProcessTime += duration;
}
}
};
class MessagePackage {
public:
typedef char * Buffer;
Buffer buffer;
int size;
int source;
int tag;
MPIMessageBufferBase *bufferCallback;
MessagePackage(Buffer b, int s, int src, int t, MPIMessageBufferBase *m) :
buffer(b), size(s), source(src), tag(t), bufferCallback(m) {
}
};
template<typename C>
class DummyProcessor {
public:
int process(C *msg, MessagePackage &buffer) {
return 0;
}
};
template<typename C, typename CProcessor = DummyProcessor<C> >
class MPIMessageBuffer: public MPIMessageBufferBase {
public:
static const int BUFFER_QUEUE_SOFT_LIMIT = 5;
static const int BUFFER_INSTANCES = 5;
typedef C MessageClass;
typedef CProcessor MessageClassProcessor;
typedef typename MessagePackage::Buffer Buffer;
typedef std::vector<Buffer> FreeBufferCache;
typedef std::vector<FreeBufferCache> ThreadedFreeBufferCache;
typedef std::list<MessagePackage> MessagePackageQueue;
protected:
mpi::communicator _world;
int _bufferSize;
int _messageSize;
MessageClassProcessor _processor;
float _softRatio;
int _softMaxBufferSize;
int _softNumThreads;
int _numCheckpoints;
ThreadedFreeBufferCache _freeBuffers;
int _numThreads;
int _worldSize;
int _numWorldThreads;
public:
MPIMessageBuffer(mpi::communicator &world, int messageSize,
MessageClassProcessor processor = MessageClassProcessor(),
int totalBufferSize = MPIOptions::getOptions().getTotalBufferSize(),
float softRatio = 0.90) :
_world(world, mpi::comm_duplicate), _bufferSize(totalBufferSize / _world.size() / BUFFER_INSTANCES),
_messageSize(messageSize), _processor(processor), _softRatio(
softRatio), _softNumThreads(0), _numCheckpoints(0) {
assert(getMessageSize() >= (int) sizeof(MessageClass));
assert(_softRatio >= 0.0 && _softRatio <= 1.0);
_worldSize = _world.size();
if (omp_in_parallel())
_numThreads = omp_get_num_threads();
else
_numThreads = omp_get_max_threads();
_softNumThreads = std::max(_numThreads * 3 / 4, 1);
_bufferSize /= (_numThreads*_numThreads);
_bufferSize = std::max(std::max(messageSize,MPIOptions::getOptions().getMinTransmitSize()/_numThreads), _bufferSize);
setSoftMaxBufferSize();
_numWorldThreads = _worldSize * _numThreads;
_freeBuffers.resize(_numThreads);
for (int threadId = 0; threadId < _numThreads; threadId++)
_freeBuffers[threadId].reserve(BUFFER_QUEUE_SOFT_LIMIT
* _numWorldThreads + 1);
LOG_DEBUG_OPTIONAL(1, Logger::isMaster(), "MPIMessageBuffer(): " << _numThreads << " threads, " << _bufferSize << " size " << getMessageSize() << " message size");
}
~MPIMessageBuffer() {
for (ThreadedFreeBufferCache::iterator it = _freeBuffers.begin(); it != _freeBuffers.end(); it++)
for (FreeBufferCache::iterator it2 = it->begin(); it2 != it->end(); it2++)
delete [] *it2;
_freeBuffers.clear();
}
inline mpi::communicator &getWorld() {
return _world;
}
inline int getNumThreads() const {
return _numThreads;
}
inline int getSoftNumThreads() const {
return _softNumThreads;
}
inline int getNumWorldThreads() const {
return _numWorldThreads;
}
inline int getWorldSize() const {
return _worldSize;
}
inline int getMessageSize() const {
return _messageSize;
}
inline MessageClassProcessor &getProcessor() {
return _processor;
}
void setMessageProcessor(MessageClassProcessor processor) {
_processor = processor;
}
inline int getSoftMaxBufferSize() const {
return _softMaxBufferSize;
}
void setSoftMaxBufferSize() {
_softMaxBufferSize = std::max(getMessageSize(), (int) (_bufferSize
* _softRatio));
assert(_softMaxBufferSize >= 0 && _softMaxBufferSize <= _bufferSize);
}
inline int getMaxMessageSize() const {
return getBufferSize() - sizeof(MessageClass) - sizeof(long);
}
inline int getBufferSize() const {
return _bufferSize;
}
void setBufferSize(int bufferSize) {
_bufferSize = bufferSize;
setSoftMaxBufferSize();
}
Buffer getNewBuffer() {
int threadId = omp_get_thread_num();
Buffer buf;
if (_freeBuffers[threadId].empty()) {
buf = new char[_bufferSize];
LOG_DEBUG(4, "getNewBuffer(): " << (void*) buf << " of " << _bufferSize << " ending: " << (void*) (buf + _bufferSize));
} else {
buf = _freeBuffers[threadId].back();
_freeBuffers[threadId].pop_back();
}
return buf;
}
void returnBuffer(Buffer buf) {
int threadId = omp_get_thread_num();
if (_freeBuffers[threadId].size() >= (size_t) (BUFFER_QUEUE_SOFT_LIMIT
* _numWorldThreads)) {
delete [] buf;
buf = NULL;
} else {
_freeBuffers[threadId].push_back(buf);
}
}
long processMessagePackage(MessagePackage &messagePackage) {
double duration = MPI_Wtime();
Buffer msg, start = messagePackage.buffer;
long count = 0;
int offset = 0;
while (offset < messagePackage.size) {
msg = start + offset;
LOG_DEBUG(4, "processMessagePackage(): (" << messagePackage.source
<< ", " << messagePackage.tag << "): " << (void*) msg
<< " offset: " << offset);
int trailingBytes = _processor.process((MessageClass*) msg,
messagePackage);
offset += this->getMessageSize() + trailingBytes;
this->newMessage();
count++;
}
this->threadProcess(MPI_Wtime() - duration);
return count;
}
inline int getNumCheckpoints() const {
return _numCheckpoints;
}
bool reachedCheckpoint(int checkpointFactor = 1) const {
return getNumCheckpoints() == _worldSize * checkpointFactor;
}
void resetCheckpoints() {
_numCheckpoints = 0;
}
void checkpoint() {
#pragma omp atomic
_numCheckpoints++;
LOG_DEBUG(3, "checkpoint received:" << _numCheckpoints);
}
};
template<typename C, typename CProcessor >
class MPIAllToAllMessageBuffer: public MPIMessageBuffer<C, CProcessor > {
public:
typedef MPIMessageBuffer<C, CProcessor > BufferBase;
typedef typename BufferBase::Buffer Buffer;
typedef typename BufferBase::MessagePackageQueue MessagePackageQueue;
typedef C MessageClass;
typedef CProcessor MessageClassProcessor;
static const int NUM_BUFFERS = 4;
class MessageHeader {
public:
MessageHeader() :
offset(0), threadSource(0), tag(0) {
setDummy();
}
MessageHeader(const MessageHeader ©) :
offset(copy.offset), threadSource(copy.threadSource),
tag(copy.tag), dummy(copy.dummy) {
}
MessageHeader &operator=(const MessageHeader &other) {
if (this == &other)
return *this;
offset = other.offset;
threadSource = other.threadSource;
tag = other.tag;
dummy = other.dummy;
return *this;
}
inline void reset(int _threadSource = 0, int _tag = 0) {
LOG_DEBUG(5, "MessageHeader::reset(" << _threadSource << ", "
<< _tag << "):" << (void*) this);
offset = 0;
threadSource = _threadSource;
tag = _tag;
setDummy();
}
inline void resetOffset() {
LOG_DEBUG(5, "MessageHeader::resetOffset():" << (void*) this
<< " from: " << offset);
offset = 0;
setDummy();
}
int append(int dataSize) {
LOG_DEBUG(5, "MessageHeader::append(" << dataSize << "):"
<< (void*) this << " " << offset);
offset += dataSize;
setDummy();
return offset;
}
inline bool validate() const {
return dummy == _getDummy();
}
inline int getOffset() const {
return offset;
}
inline int getThreadSource() const {
return threadSource;
}
inline int getTag() const {
return tag;
}
std::string toString() const {
std::stringstream ss;
ss << "MessageHeader(" << (void*) this << "): offset: " << offset
<< " threadSource: " << threadSource << " tag: " << tag
<< " dummy: " << dummy << " valid: " << validate();
return ss.str();
}
private:
int offset, threadSource, tag, dummy;
void setDummy() {
dummy = _getDummy();
}
int _getDummy() const {
return (offset + threadSource + tag);
}
};
class BuildBuffer {
public:
Buffer buffer;
MessageHeader header;
BuildBuffer() :
buffer(NULL), header(MessageHeader()) {
}
~BuildBuffer() {
reset();
}
void reset() {
header.reset();
if (buffer != NULL) {
delete [] buffer;
buffer = NULL;
}
}
};
class TransmitBuffer {
public:
enum StateType { EMPTY_OUT, BUILDING_OUT, READY_OUT, EMPTY_IN, BUILDING_IN, READY_IN, DRAINING_IN, UNUSED };
TransmitBuffer(int _numThreads, int _worldSize, int _numTags, int bufferSize) :
numThreads(_numThreads), worldSize(_worldSize), numTags(_numTags), buildSize(0), finalCount(0) {
dataSize = sizeof(int) + numThreads * (numThreads * numTags)
* (sizeof(MessageHeader) + bufferSize);
totalSize = getHeaderSize() + worldSize * dataSize;
jumps = new int[numThreads * worldSize * numThreads * numTags];
xmit = new char[totalSize];
// in/out displacements do not change
for (int rankDest = 0; rankDest < worldSize; rankDest++) {
getOffset(rankDest) = rankDest * dataSize;
}
threadStates.resize(numThreads);
setAllStates(UNUSED);
}
~TransmitBuffer() {
delete [] jumps;
delete [] xmit;
}
inline int getJump(int rankDest, int threadDest, int threadId = 0) {
return threadId * worldSize * numThreads * numTags + rankDest
* numThreads * numTags + threadDest;
}
inline Buffer getJumpBuffer(int rankDest, int threadDest, int threadId) {
return getBuffer(rankDest) + jumps[getJump(rankDest,threadDest,threadId)];
}
inline int &getSize(int rankDest) {
// Transmit size for each rank (includes extra int of datasize)
int *o = (int*) xmit;
return *(o + rankDest);
}
inline int &getOffset(int rankDest) {
// displacement for each rank
int *o = (int*) xmit;
return *(o + worldSize + rankDest);
}
inline int &getDataSize(int rankDest) {
// total size of the data sent
int *o = (int*) xmit;
Buffer buf = (Buffer) (o + worldSize * 2);
return *((int*) (buf + rankDest * dataSize));
}
inline Buffer getBuffer(int rankDest) {
// the data (immediately after datasize int)
return (Buffer) (&getDataSize(rankDest) + 1);
}
inline int getHeaderSize() {
return worldSize * sizeof(int) * 2;
}
inline int getBuildSize() const {
return buildSize;
}
void prepOut() {
assert( areAllInState(UNUSED) );
for (int rankDest = 0; rankDest < worldSize; rankDest++) {
getSize(rankDest) = 0;
getDataSize(rankDest) = 0;
}
buildSize = 0;
setAllStates(EMPTY_OUT);
finalCount = 0;
}
void prepIn() {
assert( areAllInState(UNUSED) );
for (int rankDest = 0; rankDest < worldSize; rankDest++) {
getSize(rankDest) = dataSize;
}
buildSize = 0;
setAllStates(EMPTY_IN);
finalCount = 0;
}
void reset() {
assert( areAllInState(UNUSED) || areAllInState(EMPTY_IN) || areAllInState(READY_OUT));
buildSize = 0;
setAllStates(UNUSED);
finalCount = 0;
}
static void AllToAll(TransmitBuffer &out, TransmitBuffer &in, mpi::communicator &world) {
// mpi_alltoall
assert(out.areAllInState(READY_OUT));
assert(in.areAllInState(EMPTY_IN));
in.setAllStates(BUILDING_IN);
MPI_Alltoallv(out.xmit + out.getHeaderSize(), &out.getSize(0),
&out.getOffset(0), MPI_BYTE, in.xmit
+ in.getHeaderSize(), &in.getSize(0),
&in.getOffset(0), MPI_BYTE, world);
out.setAllStates(UNUSED);
in.setAllStates(READY_IN);
}
// must be in critical section!
void setSize(int rankDest, int threadDest, int threadId, BuildBuffer &bb) {
int jump = getJump(rankDest, threadDest, threadId);
int &outSize = getSize(rankDest);
jumps[jump] = outSize;
int size = bb.header.getOffset();
buildSize += size;
outSize += size + sizeof(MessageHeader);
LOG_DEBUG(4, "sendReceive(): sending (" << rankDest << ", "
<< threadDest << "): " << size
<< " bytes, outSize: " << outSize << " buildSize: "
<< buildSize);
}
void setTransmitSizes(bool isFinalized) {
long bytesSend = 0, bytesRecv = 0;
setTransmitSizes(isFinalized, bytesSend, bytesRecv);
}
void setTransmitSizes(bool isFinalized, long &bytesSend, long &bytesRecv) {
if (isFinalized && buildSize == 0) {
for (int destRank = 0; destRank < worldSize; destRank++) {
getDataSize(destRank) = 0; // send no MessageHeaders
// add the (int) datasize to the total length sent so something is always sent
bytesSend += getSize(destRank) = sizeof(int);
}
} else {
// set transmitted sizes
for (int destRank = 0; destRank < worldSize; destRank++) {
int dataSize = getSize(destRank);
getDataSize(destRank) = dataSize; // includes MessageHeaders
// add the (int) datasize to the total length sent
bytesSend += getSize(destRank) += sizeof(int);
}
}
}
bool inState(StateType _state, int threadNum) const {
return threadStates[threadNum] == _state;
}
bool inState(StateType _state) const {
return inState(_state, omp_get_thread_num());
}
bool areAllInState(StateType _state) const {
for(int i = 0; i < numThreads; i++)
if ( !inState(_state, i) ) {
LOG_DEBUG(5, "areAllInState() Failed: " << toString() << " i:" << i << " ts:" << threadStates[i] << " _state: " << _state);
return false;
}
return true;
}
bool areAllReadyOut() const {
return areAllInState(READY_OUT);
}
bool isEmptyOut() const {
return inState(EMPTY_OUT);
}
bool isReadyOut() const {
return inState(READY_OUT);
}
bool isEmptyIn() const {
return inState(EMPTY_IN);
}
bool isBuildingIn() const {
return inState(BUILDING_IN);
}
bool isReadyIn() const {
return inState(READY_IN);
}
bool isUnused() const {
return inState(UNUSED);
}
void setFinal() {
#pragma omp atomic
finalCount++;
}
bool areAllFinal() {
return finalCount == numThreads;
}
void setThreadBuildingOut() {
assert(inState(EMPTY_OUT));
setThreadState(BUILDING_OUT);
}
void setThreadReadyOut() {
assert(inState(BUILDING_OUT));
setThreadState(READY_OUT);
}
void setThreadDrainingIn() {
assert(inState(READY_IN));
setThreadState(DRAINING_IN);
}
void setThreadFinishedIn() {
assert(inState(DRAINING_IN));
setThreadState(UNUSED);
}
void clearFinal() {
finalCount = 0;
}
std::string toString() const {
std::stringstream ss;
ss << "TransmitBuffer(" << (void*) this << "): {buildSize: " << buildSize << ", ";
ss << "finalCount: " << finalCount << ", ";
for(int i = 0; i < numThreads; i++)
ss << i << ": " << threadStates[i] << ", ";
ss << "}";
return ss.str();
}
private:
int numThreads, worldSize, numTags, buildSize, dataSize, totalSize, finalCount;
Buffer xmit;
int *jumps;
std::vector< StateType > threadStates;
void setThreadState(StateType _newState) {
threadStates[omp_get_thread_num()] = _newState;
}
void setAllStates(StateType _newState) {
for(int i = 0; i < numThreads; i++)
threadStates[i] = _newState;
}
};
private:
TransmitBuffer* buffers[NUM_BUFFERS];
int currentBuffer;
std::vector<std::vector<std::vector<BuildBuffer> > > buildsTWT;
int numTags;
int threadsSending;
public:
MPIAllToAllMessageBuffer(mpi::communicator &world, int messageSize,
MessageClassProcessor processor = MessageClassProcessor(),
int _numTags = 1, int totalBufferSize = MPIOptions::getOptions().getTotalBufferSize(), double softRatio = 0.90) :
BufferBase(world, messageSize, processor, totalBufferSize, softRatio),
numTags(_numTags), threadsSending(0) {
assert(!omp_in_parallel());
assert(omp_get_thread_num() == 0);
assert(numTags > 0);
int worldSize = this->getWorldSize();
int numThreads = this->getNumThreads();
buildsTWT.resize(numThreads);
for (int threadId = 0; threadId < numThreads; threadId++) {
buildsTWT[threadId].resize(worldSize);
}
for(int i = 0; i < NUM_BUFFERS; i++) {
buffers[i] = new TransmitBuffer(numThreads, worldSize, numTags, this->getBufferSize());
}
currentBuffer = 0;
for (int rankDest = 0; rankDest < worldSize; rankDest++) {
for (int threadId = 0; threadId < numThreads; threadId++) {
buildsTWT[threadId][rankDest].resize(numThreads * numTags, BuildBuffer());
for (int threadDest = 0; threadDest < (numThreads * numTags); threadDest++) {
BuildBuffer &bb = buildsTWT[threadId][rankDest][threadDest];
bb.header.reset(threadId, threadDest);
bb.buffer = this->getNewBuffer();
}
}
}
}
~MPIAllToAllMessageBuffer() {
assert(!omp_in_parallel());
for(int i = 0; i < NUM_BUFFERS; i++) {
if (buffers[i] != NULL) {
delete buffers[i];
buffers[i] = NULL;
}
}
}
private:
long sendReceive(bool isFinalized) {
assert(omp_get_max_threads() == 1 || omp_in_parallel());
if (isFinalized)
this->syncAttempt();
long iterations = 0;
double waitTime;
int thisBuffer = currentBuffer;
TransmitBuffer &last = *buffers[(thisBuffer+0) % NUM_BUFFERS];
TransmitBuffer &in = *buffers[(thisBuffer+1) % NUM_BUFFERS];
TransmitBuffer &out = *buffers[(thisBuffer+2) % NUM_BUFFERS];
//TransmitBuffer &last2 = *buffers[(thisBuffer+3) % NUM_BUFFERS];
LOG_DEBUG(3, "sendReceive(" << isFinalized << ") "
<< this->getNumMessages() << " messages "
<< this->getNumDeliveries() << " deliveries "
<< thisBuffer << " bufferCount "
<< threadsSending << " threadsSending");
// reset checkpoints before processing 'last'
if (omp_get_thread_num() == 0) {
assert(out.areAllInState( TransmitBuffer::UNUSED ));
out.prepOut();
assert(in.areAllInState( TransmitBuffer::UNUSED ));;
in.prepIn();
}
#pragma omp atomic
threadsSending++;
// ensure in, out & last buffer are all prepared
// and all threads have reset checkpoints
LOG_DEBUG(3, "sendReceive() starting barrier1, buffer: " << thisBuffer);
waitTime = MPI_Wtime();
#pragma omp barrier
this->threadWait( MPI_Wtime() - waitTime );
// make sure all threads get here before incrementing the buffer or resetting checkpoints
if (omp_get_thread_num() == 0) {
this->resetCheckpoints();
#pragma omp atomic
currentBuffer++;
}
if (isFinalized)
out.setFinal();
iterations = 1;
while (! out.isEmptyOut() )
WAIT_AND_WARN(iterations, "sendReceive() waiting for out buffer to be prepared!!! (" << TransmitBuffer::EMPTY_OUT << "): buffer: " << thisBuffer << " " << out.toString()); // spin lock
assert(out.isEmptyOut());
assert(in.isEmptyIn());
#pragma omp atomic
threadsSending--;
waitTime = MPI_Wtime();
#pragma omp barrier
this->threadWait( MPI_Wtime() - waitTime );
// make sure all threads always use the same currentBuffer (between two barriers)
LOG_DEBUG(3, "sendReceive() past barrier2, buffer: " << thisBuffer);
// now process buffers without any further thread-wide barriers
// .. master will block until all out buffers are ready
_prepBuffersByThread(out);
assert( last.isUnused() || last.isReadyIn() || last.isBuildingIn() );
// spin lock this thread until its last buffer is ready (last round's communication has finished)
waitTime = MPI_Wtime();
iterations = 1;
while ( last.isBuildingIn() )
WAIT_AND_WARN(iterations, "sendReceive() waiting for last buffer to finish building (" << TransmitBuffer::READY_IN << "): buffer: " << thisBuffer << " " << last.toString()); // spin lock
this->threadWait( MPI_Wtime() - waitTime );
long numReceived = 0;
if (last.isReadyIn())
numReceived += _processBuffersByThread(last);
if (out.areAllFinal()) {
// wait for all to process the last buffer, update checkpoints, then check it
LOG_DEBUG(2, "sendReceive() Starting areAllFinal barrier on buffer: " << thisBuffer << " " << threadsSending);
assert(out.isReadyOut());
assert(last.isUnused());
#pragma omp barrier
if (out.getBuildSize() == 0 && this->reachedCheckpoint(this->getNumThreads())) {
if (omp_get_thread_num() == 0) {
out.reset();
in.reset();
}
LOG_DEBUG_OPTIONAL(1, omp_get_thread_num() == 0, "sendReceive() areAllFinal() Found checkpoint. master stopping on buffer: " << thisBuffer << " " << threadsSending);
return numReceived;
} else {
LOG_DEBUG_OPTIONAL(2, true, "sendReceive() areAllFinal() did not reach checkpoint. buffer: " << thisBuffer << " " << threadsSending);
}
}
if (omp_get_thread_num() == 0)
{
// spin lock master until all out buffers are ready (all threads have called _prepBuffersByThread )
waitTime = MPI_Wtime();
iterations = 1;
while( ! out.areAllReadyOut() )
WAIT_AND_WARN(iterations, "sendReceive() waiting for out buffer to finish building ( " << TransmitBuffer::READY_OUT << ") on all threads: buffer: " << thisBuffer << " " << out.toString()); // spin lock
this->threadWait( MPI_Wtime() - waitTime );
assert( in.areAllInState( TransmitBuffer::EMPTY_IN) );
assert( out.areAllInState( TransmitBuffer::READY_OUT) );
out.setTransmitSizes(out.areAllFinal(), this->_sendBytes, this->_recvBytes);
LOG_DEBUG(4, "sendReceive(): Starting all2all on buffer: " << thisBuffer << " threadsSending: " << threadsSending);
waitTime = MPI_Wtime();
// mpi_alltoall
TransmitBuffer::AllToAll(out, in, this->getWorld());
this->transit(MPI_Wtime() - waitTime);
this->newMessageDelivery();
LOG_DEBUG(4, "sendReceive(): Finished all2all on buffer: " << thisBuffer << " threadsSending: " << threadsSending);
}
return numReceived;
}
public:
long sendReceive() {
return sendReceive(false);
}
int getBytesInBuffer() const {
int offset = 0;
for(int rankDest = 0 ; rankDest < this->getWorldSize(); rankDest++) {
for(int tagDest = 0 ; tagDest < (this->getNumThreads() * numTags); tagDest++) {
assert(omp_get_thread_num() < this->getNumThreads());
const BuildBuffer &bb = buildsTWT[omp_get_thread_num()][rankDest][tagDest];
offset += bb.header.getOffset();
}
}
return offset;
}
int processMessages(int sourceRank, MessageHeader *header) {
assert(header->validate());
Buffer buf = (Buffer) (header + 1);
MessagePackage msgPkg(buf, header->getOffset(), sourceRank,
header->getTag(), this);
return this->processMessagePackage(msgPkg);
}
void finalize() {
assert(omp_get_max_threads() == 1 || omp_in_parallel());
LOG_DEBUG(2, "Entering finalize()");
while (!this->reachedCheckpoint(this->getNumThreads())) {
sendReceive(true);
}
this->syncPoint();
#pragma omp barrier
}
bool isReadyToSend(int offset, int trailingBytes) {
assert(trailingBytes + this->getMessageSize() <= this->getBufferSize());
return ( ( (offset >= this->getSoftMaxBufferSize()) & (threadsSending > this->getSoftNumThreads()) )
| ((offset + trailingBytes + this->getMessageSize()) >= this->getBufferSize()) );
}
MessageClass *bufferMessage(int rankDest, int tagDest) {
return bufferMessage(rankDest, tagDest, 0);
}
MessageClass *bufferMessage(int rankDest, int tagDest, int trailingBytes) {
bool wasSent = false;
long messages = 0;
return bufferMessage(rankDest, tagDest, wasSent, messages,
trailingBytes);
}
// copies msg as the next message in the buffer
void bufferMessage(int rankDest, int tagDest, MessageClass *msg,
int trailingBytes = 0) {
char *buf = (char *) bufferMessage(rankDest, tagDest, trailingBytes);
memcpy(buf, (char *) msg, this->getMessageSize() + trailingBytes);
}
MessageClass *bufferMessage(int rankDest, int tagDest, bool &wasSent,
long &messages) {
return bufferMessage(rankDest, tagDest, wasSent, messages, 0);
}
// returns a pointer to the next message. User can use this to create message
MessageClass *bufferMessage(int rankDest, int tagDest, bool &wasSent,
long &messages, int trailingBytes) {
int threadId = omp_get_thread_num();
assert(threadId < this->getNumThreads() && rankDest < this->getWorldSize() && tagDest < this->numTags * this->getNumThreads());
BuildBuffer &bb = buildsTWT[threadId][rankDest][tagDest];
while (isReadyToSend(bb.header.getOffset(), trailingBytes))
messages += sendReceive(false);
assert(bb.buffer != NULL);
MessageClass *buf =
(MessageClass *) (bb.buffer + bb.header.getOffset());
int msgSize = this->getMessageSize() + trailingBytes;
bb.header.append(msgSize);
this->newMessage();
LOG_DEBUG(5, "bufferMessage(" << rankDest << ", " << tagDest << ", "
<< wasSent << ", " << messages << ", " << trailingBytes
<< "): " << (void*) buf << " size: " << msgSize);
assert(((Buffer)buf) + msgSize < bb.buffer + this->getBufferSize());
return buf;
}
private:
void _prepBuffersByThread(TransmitBuffer &out) {
assert(omp_get_max_threads() == 1 || omp_in_parallel());
int threadId = omp_get_thread_num();
int numThreads = this->getNumThreads();
int worldSize = this->getWorldSize();
out.setThreadBuildingOut();
double waitTime = MPI_Wtime();
#pragma omp critical
{
waitTime = MPI_Wtime() - waitTime;
// allocate the out message headers
for (int rankDest = 0; rankDest < worldSize; rankDest++) {
for (int threadDest = 0; threadDest < (numThreads * numTags); threadDest++) {
assert(threadId < this->getNumThreads() && rankDest < this->getWorldSize() && threadDest < this->numTags * this->getNumThreads());
BuildBuffer &bb = buildsTWT[threadId][rankDest][threadDest];
assert(bb.header.validate());
out.setSize(rankDest, threadDest, threadId, bb);
}
}