forked from PaddlePaddle/Paddle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParameterServer2.cpp
1573 lines (1394 loc) · 56.5 KB
/
ParameterServer2.cpp
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
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "ParameterServer2.h"
#include <algorithm>
#include <fstream>
#include "paddle/math/SIMDFunctions.h"
#include "paddle/parameter/AverageOptimizer.h"
#include "paddle/parameter/FirstOrderOptimizer.h"
#include "paddle/utils/Flags.h"
#include "paddle/parameter/OptimizerFunctions.h"
#include "paddle/parameter/OptimizerWithRegularizer.h"
#include "paddle/parameter/ParameterUpdateFunctions.h"
#include "paddle/parameter/ParameterOptimizer.h"
#include "paddle/parameter/Regularizer.h"
#include "paddle/utils/Stat.h"
#include "paddle/utils/GlobalConstants.h"
P_DEFINE_int32(pserver_num_threads, 1, "number of threads for sync op exec");
P_DEFINE_double(async_lagged_ratio_min, 1.0,
"control config_.async_lagged_grad_discard_ratio() min value");
P_DEFINE_double(
async_lagged_ratio_default, 1.5,
"if async_lagged_grad_discard_ratio is not set in trainer_config.conf"
"use it as defalut value");
namespace paddle {
const std::string ParameterServer2::kRetMsgInvalidMatrixHandle =
"Invalid matrix handle";
const std::string ParameterServer2::kRetMsgInvalidVectorHandle =
"Invalid vector handle";
const std::string ParameterServer2::kRetMsgUnknownOperation =
"Unknown operation";
ParameterServer2::ParameterServer2(const std::string& addr, int port,
int rdmaCpu)
: ProtoServer(addr, port, rdmaCpu),
dataSize_(0),
size_(0),
gradientReadyBarrier_(FLAGS_num_gradient_servers + 1),
parameterReadyBarrier_(FLAGS_num_gradient_servers + 1),
passBarrier_(FLAGS_num_gradient_servers + 1),
numPassFinishClients_(0),
allClientPassFinish_(false),
serverId_(-1),
batchId_(-1) {
/**
* register function for remote client calling, these functions
* will be mapped to a data structure for quick looking up. each
* request from trainer can contains one function name to indicate
* remote action. this architecture looks like rpc style for pserver.
*/
REGISTER_SERVICE_FUNCTION_EX(ParameterServer2, sendParameter);
REGISTER_SERVICE_FUNCTION_EX(ParameterServer2, sendData);
REGISTER_SERVICE_FUNCTION(ParameterServer2, setConfig);
REGISTER_SERVICE_FUNCTION(ParameterServer2, setStatus);
REGISTER_SERVICE_FUNCTION(ParameterServer2, getStatus);
REGISTER_SERVICE_FUNCTION(ParameterServer2, doOperation);
REGISTER_SERVICE_FUNCTION(ParameterServer2, createVector);
REGISTER_SERVICE_FUNCTION(ParameterServer2, releaseVector);
REGISTER_SERVICE_FUNCTION(ParameterServer2, createMatrix);
REGISTER_SERVICE_FUNCTION(ParameterServer2, releaseMatrix);
REGISTER_SERVICE_FUNCTION(ParameterServer2, waitPassStart);
REGISTER_SERVICE_FUNCTION(ParameterServer2, waitPassFinish);
REGISTER_SERVICE_FUNCTION(ParameterServer2, synchronize);
REGISTER_SERVICE_FUNCTION(ParameterServer2, asyncFinishPass);
REGISTER_SERVICE_FUNCTION(ParameterServer2, loadValueVector);
REGISTER_SERVICE_FUNCTION(ParameterServer2, saveValueVector);
/// thread pool for parallelizing some computations
if (FLAGS_pserver_num_threads > 1) {
syncThreadPool_.reset(new SyncThreadPool(FLAGS_pserver_num_threads, false));
}
}
bool ParameterServer2::init() {
vectors_.resize(NUM_PARAMETER_TYPES);
configMap_.clear();
numSamplesProcessed_ = 0;
cost_ = 0;
char* mpienv = getenv("OMPI_COMM_WORLD_SIZE");
if (mpienv != NULL) {
mpiSize_ = atoi(mpienv);
} else {
mpiSize_ = 1;
}
status_ = PSERVER_STATUS_NOT_SET;
dataMems_.resize(FLAGS_num_gradient_servers);
synchronizeBarriers_.resize(SyncObject_ARRAYSIZE);
for (auto& barrier : synchronizeBarriers_) {
barrier.reset(new ThreadBarrier(FLAGS_num_gradient_servers));
}
// initialization for dicarding lagging gradient
asyncUpdateSteps_ = 0;
asyncTrainerSteps_.resize(FLAGS_num_gradient_servers);
asyncTrainerSteps_.assign(asyncTrainerSteps_.size(), 0);
asyncLaggedGradientsNum_ = 0;
asyncUpdateStat_.resize(static_cast<int>(FLAGS_num_gradient_servers *
FLAGS_async_lagged_ratio_default));
asyncUpdateStat_.assign(asyncUpdateStat_.size(), 0);
asyncTrainerDiscardStat_.resize(FLAGS_num_gradient_servers);
asyncTrainerDiscardStat_.assign(asyncTrainerDiscardStat_.size(), 0);
asyncTrainerCommitStat_.resize(FLAGS_num_gradient_servers);
asyncTrainerCommitStat_.assign(asyncTrainerCommitStat_.size(), 0);
return true;
}
void ParameterServer2::getStatus(const GetStatusRequest& request,
ProtoResponseCallback callback) {
(void)request;
GetStatusResponse response;
response.set_status(status_);
callback(response);
}
void ParameterServer2::setStatus(const SetStatusRequest& request,
ProtoResponseCallback callback) {
status_ = request.status();
SetStatusResponse response;
callback(response);
}
void ParameterServer2::setConfig(const SetConfigRequest& request,
ProtoResponseCallback callback) {
{
std::lock_guard<RWLock> guard(parameterMutex_);
serverId_ = request.server_id();
isSparseServer_ = request.is_sparse_server();
if (!request.save_dir().empty()) {
mkDir(request.save_dir().c_str());
}
for (const auto& config : request.param_configs()) {
CHECK(!configMap_.count(config.para_id()))
<< "Duplicated parameter name: " << config.name();
configMap_[config.para_id()] = config;
CHECK_EQ(config.sparse_remote_update(), isSparseServer_);
}
config_ = request.opt_config();
if (config_.algorithm() == TrainAlgorithm::AsyncSGD) {
auto asyncLaggedRatio = config_.async_lagged_grad_discard_ratio();
if (asyncLaggedRatio <= FLAGS_async_lagged_ratio_min) {
LOG(INFO) << "WARNING: async_lagged_grad_discard_ratio is too small"
<< "reset to default, async_lagged_grad_discard_ratio = "
<< FLAGS_async_lagged_ratio_default;
asyncLaggedRatio = FLAGS_async_lagged_ratio_default;
}
asyncLaggedThreshold_ =
static_cast<int64_t>(FLAGS_num_gradient_servers * asyncLaggedRatio);
LOG(INFO) << "discard lagged async gradient ratio: " << asyncLaggedRatio
<< " asyncLaggedhreshold: " << asyncLaggedThreshold_;
}
if (isSparseServer_ && config_.num_batches_per_send_parameter() > 1) {
/// sparse server must NOT use local update mode
config_.set_num_batches_per_send_parameter(1);
}
if (config_.num_batches_per_send_parameter() > 1 &&
config_.center_parameter_update_method() == "average") {
/// scaling L1/L2 decay rate as large as L1/L2 apply in trainer
/// if parameter regularization in pserver
for (auto& pair : configMap_) {
ParameterConfig& config = pair.second;
if (config_.num_batches_per_send_parameter() ==
config.num_batches_regularization()) {
real scale =
config_.delta_add_rate() * config.num_batches_regularization();
if (config_.algorithm() == "sgd") {
scale *= FLAGS_num_gradient_servers;
}
config.set_decay_rate(config.decay_rate() * scale);
if (config.decay_rate() > 0.1f) {
LOG(FATAL) << "L2 decay=" << config.decay_rate()
<< " for parameter:" << config.name()
<< " is too large after scale in pserver!";
}
config.set_decay_rate_l1(config.decay_rate_l1() * scale);
if (config.decay_rate_l1() > 0.1f) {
LOG(FATAL) << "L1 decay=" << config.decay_rate_l1()
<< " for parameter:" << config.name()
<< " is too large after scale in pserver!";
}
LOG(INFO) << "parameter:" << config.name()
<< " decay apply in pserver,"
<< " L1 decay=" << config.decay_rate_l1()
<< " L2 decay=" << config.decay_rate();
}
}
}
}
SetConfigResponse response;
callback(response);
/// always defined, barrier slowest node function need it.
statSet_.reset(new StatSet("ParameterServer" + std::to_string(serverId_)));
}
real bufferSum(const std::vector<ParameterServer2::Buffer>& buffers) {
real sum = 0;
for (const auto buffer : buffers) {
for (size_t i = 0; i < buffer.size; ++i) {
sum += buffer.base[i];
}
}
return sum;
}
void ParameterServer2::mergeSegments(BlockSegments* segments) {
if (segments->empty()) {
return;
}
std::sort(segments->begin(), segments->end());
auto curr = segments->begin();
for (auto it = segments->begin(); it != segments->end(); ++it) {
if (it->first <= curr->second) {
curr->second = std::max(curr->second, it->second);
} else {
++curr;
*curr = *it;
}
}
++curr;
segments->erase(curr, segments->end());
}
void ParameterServer2::setParameter(const SendParameterRequest& request,
std::vector<Buffer>& inputBuffers,
SendParameterResponse* response,
std::vector<Buffer>* outputBuffers) {
(void)response;
(void)outputBuffers;
LOG(INFO) << "pserver: setParameter";
std::lock_guard<RWLock> guard(parameterMutex_);
int64_t numBlocks = blockIdMap_.size();
CHECK_EQ(blockIdMap_.size(), blockOffsetMap_.size());
/// total bytes for all the added blocks
int64_t totalSize = size_;
std::vector<int64_t> offsets;
offsets.reserve(request.blocks_size());
std::vector<int64_t> blockIds;
blockIds.reserve(request.blocks_size());
int bufferIndex = 0;
for (const auto& block : request.blocks()) {
/// block size for parameter(e.g. 128 for sparse row, 1K for dense)
uint64_t blockSize = getParameterConfig(block).parameter_block_size();
BlockKey key(block.para_id(), block.block_id());
if (inputBuffers.size()) { // if !=PSERVER_UPDATE_MODE_SET_PARAM_ZERO
Buffer buffer = inputBuffers[bufferIndex];
++bufferIndex;
CHECK_EQ(buffer.size, block.block_size())
<< "data size is too big:"
<< " block_size=" << block.block_size()
<< " data_size=" << buffer.size;
}
/// add a new block
if (blockIdMap_.count(key) == 0) {
blockOffsetMap_[key] = totalSize;
blockIdMap_[key] = numBlocks;
++numBlocks;
totalSize += blockSize;
}
offsets.push_back(blockOffsetMap_[key]);
blockIds.push_back(blockIdMap_[key]);
}
size_ = totalSize;
LOG(INFO) << "pserver: new cpuvector: size=" << size_;
if (!vectors_[PARAMETER_VALUE]) {
/// vectors_
const auto types = sgdOptimizerGetTypes(config_, true /*inPserver*/);
for (const auto type : types) {
vectors_[type].reset(new CpuVector(size_));
vectors_[type]->zeroMem();
}
blockInfos_.resize(numBlocks);
for (auto& info : blockInfos_) {
info.lock.reset(new std::mutex());
}
} else {
CHECK_EQ((size_t)size_, vectors_[PARAMETER_VALUE]->getSize())
<< "Currently adding new blocks is not supported. "
<< "All blocks must be added in one setParameter call";
}
VectorPtr buf = vectors_[PARAMETER_VALUE];
usedSegments_.reserve(offsets.size());
/// if offsets is empty, means parameter_block_size is too big or too many
/// nodes.
if (offsets.empty()) {
LOG(WARNING) << "in setParameter: offsets is empty";
}
for (size_t i = 0; i < offsets.size(); ++i) {
size_t blockId = blockIds[i];
BlockInfo& info = blockInfos_[blockId];
const ParameterConfig& config = getParameterConfig(request.blocks(i));
info.config = &config;
info.offset = offsets[i];
info.optimizer.reset(sgdOptimizerCreate(
config_, config, config.sparse_remote_update(), true /*inPserver*/));
if (config.sparse_remote_update()) {
size_t width = config.dims(1);
CHECK_EQ(config.parameter_block_size(), width)
<< "block size: " << config.parameter_block_size()
<< "width : " << width;
}
info.optimizer->init(1, info.config);
usedSegments_.push_back(std::make_pair(offsets[i],
offsets[i] + request.blocks(i).block_size()));
}
mergeSegments(&usedSegments_);
if (request.update_mode() == PSERVER_UPDATE_MODE_SET_PARAM) {
/// copy param from trainer
for (size_t i = 0; i < offsets.size(); ++i) {
Buffer buffer = inputBuffers[i];
real* start = buf->getPoint(offsets[i]);
CHECK_LE(offsets[i] + buffer.size, buf->getSize());
memcpy(start, buffer.base, sizeof(real) * buffer.size);
}
} else {
CHECK(request.update_mode() == PSERVER_UPDATE_MODE_SET_PARAM_ZERO);
/// nothing to do, value vector zero mem already
}
}
void ParameterServer2::addGradient(const SendParameterRequest& request,
std::vector<Buffer>& inputBuffers,
SendParameterResponse* response,
std::vector<Buffer>* outputBuffers) {
VLOG(1) << "pserver: addGradient";
/// forwardbackward delta from all trainers
/// indicate the fluctuation caused by forwardbackward.
#ifndef PADDLE_METRIC_LEARNING
// @TODO(yanfei):
// add support tuning forwardbackward balance for metric learning
if (!numPassFinishClients_) {
REGISTER_BARRIER_DELTA_SERVER_SET(
*statSet_, "forwardbackwardDelta", FLAGS_num_gradient_servers,
request.trainer_id(), request.forwardbackward_time(),
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
#endif
{
/// approximately pure network overhead
REGISTER_TIMER_DYNAMIC_SET(
"pushRecv", timeToMicroSecond(*handleRequestBegin_), -1, *statSet_);
}
#ifndef PADDLE_DISABLE_TIMER
gettimeofday(&(*addGradBegin_), nullptr);
#endif
/// barrier fluctuation caused by network and previous forwardbackward
if (!numPassFinishClients_) {
REGISTER_BARRIER_TIMER_SERVER_SET(
*statSet_, "handleReqBegin", FLAGS_num_gradient_servers,
request.trainer_id(), (*handleRequestBegin_),
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
if (!numPassFinishClients_) {
REGISTER_BARRIER_TIMER_SERVER(
*statSet_, "addGradBegin", FLAGS_num_gradient_servers,
request.trainer_id(),
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
{
REGISTER_TIMER_DYNAMIC("addGradCore", -1, *statSet_);
ReadLockGuard guard(parameterMutex_);
int bufferIndex = 0;
for (const auto& block : request.blocks()) {
int64_t offset = getBlockOffset(block);
CHECK_GE(offset, 0) << "Only existing parameter block is allowed: "
<< " id=" << block.para_id()
<< " block id=" << block.block_id();
int64_t blockId = getBlockId(block);
CHECK_GE(blockId, 0) << "Only existing parameter block is allowed: "
<< " id=" << block.para_id()
<< " block id=" << block.block_id();
Buffer buffer = inputBuffers[bufferIndex];
++bufferIndex;
const real* gradientBuffer = buffer.base;
real* gradientSumBuffer = vectors_[PARAMETER_GRADIENT]->getPoint(offset);
size_t size = buffer.size;
BlockInfo& info = blockInfos_[blockId];
const ParameterConfig& config = getParameterConfig(blockId);
if (config.sparse_remote_update()) {
CHECK_EQ(size, config.parameter_block_size());
} else { // dense
CHECK_LE(size, config.parameter_block_size());
}
std::lock_guard<std::mutex> guard(*info.lock);
simd::addTo(gradientSumBuffer, gradientBuffer, size);
}
if (!numPassFinishClients_) {
REGISTER_BARRIER_TIMER_SERVER(
*statSet_, "addGradCoreFinish", FLAGS_num_gradient_servers,
request.trainer_id(),
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
}
if (request.batch_status() == BATCH_FINISH ||
request.batch_status() == BATCH_START_AND_FINISH) {
numSamplesProcessed_ += request.num_samples();
cost_ += request.cost();
VLOG(1) << "num samples: " << numSamplesProcessed_
<< ", new cost:" << cost_;
/// numPassFinishClients_ means some trainer has entered finishPass
if (!numPassFinishClients_) {
REGISTER_SLOW_NODES_PROBE(
*statSet_, "SLOW_NODES", FLAGS_num_gradient_servers,
request.trainer_id(),
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
/// notify doOperation gradient ready
gradientReadyBarrier_.wait();
/// if wait pass finish does not start, do check
if (!numPassFinishClients_) {
CHECK_BARRIER_TIMER(*statSet_, "SLOW_NODES", FLAGS_num_gradient_servers,
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
/// barrier performance while all parameter add is finished
/// can indicate the fluctation caused by computation at pserver.
if (!numPassFinishClients_) {
REGISTER_BARRIER_TIMER_SERVER(
*statSet_, "paraReady", FLAGS_num_gradient_servers,
request.trainer_id(),
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
/// wait doOperation finish
parameterReadyBarrier_.wait();
VLOG(1) << "start send back";
{
/// total time except overhead of network.
REGISTER_TIMER_DYNAMIC_SET("sendParaNoRecvNoSend",
timeToMicroSecond(*addGradBegin_), -1,
*statSet_);
}
}
}
bool ParameterServer2::asyncGrdientCommitCheckAndStat(
const SendParameterRequest& request) {
const auto trainerId = request.trainer_id();
int64_t trainerSteps = asyncTrainerSteps_[trainerId];
CHECK_GE(asyncUpdateSteps_, trainerSteps)
<< " async update steps overflows "
<< " trainer id: " << trainerId
<< " async update steps in pserver: " << asyncUpdateSteps_
<< " async update steps in request: " << trainerSteps;
asyncUpdateSteps_++;
bool commitGradient = true;
int64_t delta = asyncUpdateSteps_ - trainerSteps;
if (delta >= asyncLaggedThreshold_) {
VLOG(1) << "discard Async Update: "
<< " trainer id: " << trainerId
<< " pserver steps: " << asyncUpdateSteps_
<< " request steps: " << trainerSteps;
asyncLaggedGradientsNum_++;
commitGradient = false;
}
/// stat on lagged steps, to get total discard distribution
if (static_cast<size_t>(delta) < asyncUpdateStat_.size()) {
asyncUpdateStat_[delta]++;
} else {
asyncUpdateStat_[asyncUpdateStat_.size() - 1]++;
}
/// stat on trainerId and discard, to get trainer condition
if (commitGradient) {
asyncTrainerCommitStat_[trainerId]++;
} else {
asyncTrainerDiscardStat_[trainerId]++;
}
return commitGradient;
}
void ParameterServer2::printAsyncGradientCommitStatAndReset() {
std::stringstream statFormat;
if (asyncUpdateSteps_) {
statFormat << "async discard gradients stat: " << std::endl;
statFormat << "serverId: " << serverId_
<< " serverType: " << isSparseServer_
<< " total updates: " << asyncUpdateSteps_
<< " discard updates: " << asyncLaggedGradientsNum_
<< " discard ratio: "
<< (real)asyncLaggedGradientsNum_ / (real)asyncUpdateSteps_;
statFormat << std::endl;
statFormat << std::endl;
statFormat << "Async Gradient Update Steps distribution: " << std::endl
<< "Sample: 1:1912(0.00284449) means "
<< "the updates step=1 count 1912 times "
<< "and account for 0.284449% of total updates" << std::endl;
size_t index = 0;
for (const auto& stat : asyncUpdateStat_) {
statFormat << index << ":" << stat << "("
<< (real)stat / (real)asyncUpdateSteps_ << ") ";
index++;
}
statFormat << std::endl;
statFormat << std::endl;
statFormat << "Async Gradient Discard based on trainer_id: " << std::endl
<< "Sample: 2:22(0.0016363) means "
<< "total discarded updates from trainer_id=2 count 22 "
<< "and account for 0.16363% of all updates from trainer_id=2"
<< std::endl;
for (auto i = 0; i < FLAGS_num_gradient_servers; i++) {
real ratio =
(real)asyncTrainerDiscardStat_[i] /
(real)(asyncTrainerCommitStat_[i] + asyncTrainerDiscardStat_[i]);
statFormat << i << ":" << asyncTrainerDiscardStat_[i] << "(" << ratio
<< ")"
<< " ";
}
LOG(INFO) << statFormat.str();
/// reset stat
asyncUpdateSteps_ = 0;
asyncTrainerSteps_.assign(asyncTrainerSteps_.size(), 0);
asyncLaggedGradientsNum_ = 0;
asyncUpdateStat_.assign(asyncUpdateStat_.size(), 0);
asyncTrainerDiscardStat_.assign(asyncTrainerDiscardStat_.size(), 0);
asyncTrainerCommitStat_.assign(asyncTrainerCommitStat_.size(), 0);
}
}
static ThreadLocal<std::vector<bool>> localBlockBitset_;
void ParameterServer2::asyncSGD(const SendParameterRequest& request,
std::vector<Buffer>& inputBuffers,
SendParameterResponse* response,
std::vector<Buffer>* outputBuffers) {
int64_t numBlocks = blockIdMap_.size();
auto& localBlockBitset = *localBlockBitset_;
if (isSparseServer_) {
if (localBlockBitset.empty()) {
localBlockBitset.resize(numBlocks);
}
localBlockBitset.assign(numBlocks, false);
}
ReadLockGuard guard(parameterMutex_);
if (request.send_back_parameter()) {
outputBuffers->reserve(request.blocks_size());
}
bool commitGradient = asyncGrdientCommitCheckAndStat(request);
VectorPtr* vecs = Parameter::getTlsTempBufs();
size_t bufferIndex = 0;
for (const auto& block : request.blocks()) {
int64_t offset = getBlockOffset(block);
CHECK_GE(offset, 0) << "Only existing parameter block is allowed: "
<< " id=" << block.para_id()
<< " block id=" << block.block_id();
int64_t blockId = getBlockId(block);
CHECK_GE(blockId, 0) << "Only existing parameter block is allowed: "
<< " id=" << block.para_id() << " block id=" << block.block_id();
Buffer buffer = inputBuffers[bufferIndex];
++bufferIndex;
size_t size = buffer.size;
BlockInfo& info = blockInfos_[blockId];
const ParameterConfig& config = getParameterConfig(blockId);
std::lock_guard<std::mutex> guard(*info.lock);
/// gradients are too obsolete, will be discarded
if (commitGradient) {
info.optimizer->startBatch(numSamplesProcessed_);
for (const auto type : info.optimizer->getParameterTypes()) {
vecs[type]->subVecFrom(*vectors_[type], offset, size);
}
vecs[PARAMETER_GRADIENT]->subVecFrom(buffer.base, 0, size);
info.optimizer->update(vecs, config, isSparseServer_ ? 0 : -1);
if (auto callback = info.optimizer->needSpecialTraversal(config)) {
blockTraverse(info, config, offset, size, vecs, callback);
}
info.optimizer->finishBatch();
}
if (commitGradient && isSparseServer_) {
localBlockBitset[blockId] = true;
}
if (!isSparseServer_ && request.send_back_parameter()) { // dense
int type = request.send_back_parameter_type();
sendBackParameter(block, type, response, &buffer, outputBuffers);
}
} /// foreach block
asyncTrainerSteps_[request.trainer_id()] = asyncUpdateSteps_;
if (commitGradient && isSparseServer_) {
/// find blocks that trainer do not request update
for (int64_t blockId = 0; blockId < numBlocks; ++blockId) {
if (localBlockBitset[blockId]) {
continue;
}
BlockInfo& info = blockInfos_[blockId];
const ParameterConfig& config = *info.config;
size_t size = config.parameter_block_size();
std::lock_guard<std::mutex> guard(*info.lock);
info.optimizer->startBatch(numSamplesProcessed_);
if (auto callback = info.optimizer->needSpecialTraversal(config)) {
blockTraverse(info, config, info.offset, size, vecs, callback);
}
info.optimizer->finishBatch();
}
}
if (commitGradient && (request.batch_status() == BATCH_FINISH ||
request.batch_status() == BATCH_START_AND_FINISH)) {
numSamplesProcessed_ += request.num_samples();
}
/// show some performance log if needed
if (request.trainer_id() == 0) {
/// batchId_ is approximately equal to "real batchId_"
batchId_++;
tuningAsyncsgdMidOutput();
}
}
void ParameterServer2::getParameter(const SendParameterRequest& request,
std::vector<Buffer>& inputBuffers,
SendParameterResponse* response,
std::vector<Buffer>* outputBuffers) {
(void)inputBuffers;
LOG(INFO) << "pserver: getParameter";
ReadLockGuard guard(parameterMutex_);
for (const auto& block : request.blocks()) {
int type = request.send_back_parameter_type();
sendBackParameter(block, type, response, outputBuffers);
}
}
void ParameterServer2::getParameterSparse(const SendParameterRequest& request,
std::vector<Buffer>& inputBuffers,
SendParameterResponse* response,
std::vector<Buffer>* outputBuffers) {
(void)inputBuffers;
auto& buffer = *readWriteBuffer_;
size_t numReals = 0;
for (const auto& block : request.blocks()) {
numReals += getParameterConfig(block).dims(1);
}
buffer.resize(numReals);
VLOG(3) << "pserver: getParameterSparse, numReals=" << numReals;
ReadLockGuard guard(parameterMutex_);
size_t offset = 0;
for (const auto& block : request.blocks()) {
size_t width = getParameterConfig(block).dims(1);
Buffer buf = {buffer.data() + offset, width};
int type = request.send_back_parameter_type();
sendBackParameterSparse(block, type, response, &buf, width, outputBuffers);
offset += width;
}
}
void ParameterServer2::sendBackParameter(const ParameterBlock& block,
int parameterType,
SendParameterResponse* response,
std::vector<Buffer>* outputBuffers) {
ParameterBlock* returnBlock = response->add_blocks();
returnBlock->set_para_id(block.para_id());
returnBlock->set_block_id(block.block_id());
returnBlock->set_begin_pos(block.begin_pos());
returnBlock->set_block_size(block.block_size());
int64_t offset = getBlockOffset(block);
CHECK_GE(offset, 0) << "Only existing parameter block is allowed: "
<< " id=" << block.para_id() << " block id=" << block.block_id();
real* valueBuffer = vectors_[parameterType]->getPoint(offset);
outputBuffers->push_back({valueBuffer, block.block_size()});
}
void ParameterServer2::sendBackParameter(const ParameterBlock& block,
int parameterType,
SendParameterResponse* response,
Buffer* buffer,
std::vector<Buffer>* outputBuffers) {
ParameterBlock* returnBlock = response->add_blocks();
returnBlock->set_para_id(block.para_id());
returnBlock->set_block_id(block.block_id());
returnBlock->set_begin_pos(block.begin_pos());
returnBlock->set_block_size(block.block_size());
int64_t offset = getBlockOffset(block);
CHECK_GE(offset, 0) << "Only existing parameter block is allowed: "
<< " id=" << block.para_id() << " block id=" << block.block_id();
size_t size = buffer->size;
real* valueBuffer = vectors_[parameterType]->getPoint(offset);
/// copy to second buffer to avoid to be polluted by other request
memcpy(buffer->base, valueBuffer, sizeof(real) * size);
outputBuffers->push_back({buffer->base, size});
}
void ParameterServer2::sendBackParameterSparse(
const ParameterBlock& block, int parameterType,
SendParameterResponse* response, Buffer* buffer, size_t width,
std::vector<Buffer>* outputBuffers) {
ParameterBlock* returnBlock = response->add_blocks();
returnBlock->set_para_id(block.para_id());
returnBlock->set_block_id(block.block_id());
returnBlock->set_begin_pos(block.begin_pos());
returnBlock->set_block_size(block.block_size());
int64_t offset = getBlockOffset(block);
CHECK_GE(offset, 0) << "Only existing parameter block is allowed: "
<< " id=" << block.para_id() << " block id=" << block.block_id();
real* valueBuffer = vectors_[parameterType]->getPoint(offset);
CHECK_EQ(buffer->size, width);
memcpy(buffer->base, valueBuffer, width * sizeof(real));
outputBuffers->push_back(*buffer);
}
void ParameterServer2::readAllBlocks(
MsgReader* msgReader, std::vector<ParameterServer2::Buffer>* buffers) {
auto& buffer = *readWriteBuffer_;
size_t numBlocks = msgReader->getNumBlocks();
buffer.resizeWithAlignHints(msgReader->getTotalLength()/sizeof(real),
numBlocks);
std::vector<void*> bufs(numBlocks);
buffers->clear();
buffers->reserve(numBlocks);
buffer.resetAlignAlloc();
for (size_t i = 0; i < numBlocks; ++i) {
size_t len = msgReader->getBlockLength(i);
CHECK_EQ(len % sizeof(real), (size_t)0);
size_t size = len / sizeof(real);
bufs[i] = buffer.nextBlock(size);
buffers->push_back({(real*)bufs[i], size});
}
msgReader->readBlocks(bufs);
}
void ParameterServer2::sendParameter(const SendParameterRequest& request,
std::unique_ptr<MsgReader> msgReader,
ProtoResponseCallbackEx callback) {
SendParameterResponse response;
std::vector<Buffer> inputBuffers;
std::vector<Buffer> outputBuffers;
readAllBlocks(msgReader.get(), &inputBuffers);
msgReader.reset();
switch (request.update_mode()) {
case PSERVER_UPDATE_MODE_SET_PARAM:
case PSERVER_UPDATE_MODE_SET_PARAM_ZERO:
setParameter(request, inputBuffers, &response, &outputBuffers);
break;
case PSERVER_UPDATE_MODE_GET_PARAM:
getParameter(request, inputBuffers, &response, &outputBuffers);
break;
case PSERVER_UPDATE_MODE_GET_PARAM_SPARSE:
getParameterSparse(request, inputBuffers, &response, &outputBuffers);
break;
case PSERVER_UPDATE_MODE_ASYNC_SGD:
asyncSGD(request, inputBuffers, &response, &outputBuffers);
break;
case PSERVER_UPDATE_MODE_ADD_GRADIENT:
addGradient(request, inputBuffers, &response, &outputBuffers);
break;
case PSERVER_UPDATE_MODE_AVERAGE_PARAMETER:
break;
}
switch (request.update_mode()) {
case PSERVER_UPDATE_MODE_ADD_GRADIENT:
(*requestVec_).push_back(request);
(*callbackVec_).push_back(callback);
if (request.batch_status() == BATCH_FINISH ||
request.batch_status() == BATCH_START_AND_FINISH) {
for (size_t i = 0; i < (*requestVec_).size(); i++) {
ReadLockGuard guard(parameterMutex_);
SendParameterRequest& request = (*requestVec_)[i];
SendParameterResponse responseTemp;
std::vector<iovec> outputIovs;
if (request.send_back_parameter()) {
CHECK(!isSparseServer_);
std::vector<Buffer> outputBuffersTemp;
for (const auto& block : request.blocks()) {
int type = request.send_back_parameter_type();
sendBackParameter(block, type, &responseTemp, &outputBuffersTemp);
}
outputIovs.reserve(outputBuffersTemp.size());
for (auto buffer : outputBuffersTemp) {
outputIovs.push_back({buffer.base, buffer.size * sizeof(real)});
}
}
ProtoResponseCallbackEx& callbackTemp = (*callbackVec_)[i];
callbackTemp(responseTemp, outputIovs);
}
(*requestVec_).clear();
(*callbackVec_).clear();
/// barrier perfromance while all data are send finished.
/// indicates network flucatuation for big message.
if (!numPassFinishClients_) {
REGISTER_BARRIER_TIMER_SERVER(
*statSet_, "sendParamFinish", FLAGS_num_gradient_servers,
request.trainer_id(),
isSparseServer_ ? "_sparseUpdater" : "_denseUpdater");
}
/// all time exhausted in parameterServer for big message.
/// it contains network and computation at pserver.
{
/// total time including overhead of network.
REGISTER_TIMER_DYNAMIC_SET("sendParaTotal",
timeToMicroSecond(*handleRequestBegin_),
-1, *statSet_);
}
/// all time exhausted in pserverServer except recieve network.
{
/// total time except overhead of network receive
REGISTER_TIMER_DYNAMIC_SET("sendParaNoRecv",
timeToMicroSecond(*addGradBegin_), -1,
*statSet_);
}
}
break;
case PSERVER_UPDATE_MODE_SET_PARAM:
case PSERVER_UPDATE_MODE_SET_PARAM_ZERO:
case PSERVER_UPDATE_MODE_GET_PARAM:
case PSERVER_UPDATE_MODE_GET_PARAM_SPARSE:
case PSERVER_UPDATE_MODE_ASYNC_SGD:
case PSERVER_UPDATE_MODE_AVERAGE_PARAMETER:
std::vector<iovec> outputIovs;
outputIovs.reserve(outputBuffers.size());
for (auto buffer : outputBuffers) {
outputIovs.push_back({buffer.base, buffer.size * sizeof(real)});
}
callback(response, outputIovs);
break;
}
}
template <typename Dtype>
void ParameterServer2::reduceAndSendData(const SendDataRequest& request,
std::unique_ptr<MsgReader>& msgReader,
ProtoResponseCallbackEx& callback) {
SendDataResponse response;
response.set_type(request.type());
response.set_server_id(serverId_);
auto sendData = reinterpret_cast<Dtype*>(dataMems_[0].get()->getBuf());
size_t rawMemSize = dataMems_[0].get()->getSize();
CHECK_EQ(rawMemSize % sizeof(Dtype), 0U);
size_t dataMemSize = rawMemSize / sizeof(Dtype);
for (size_t i = 1; i < dataMems_.size(); ++i) {
CHECK_EQ(dataMems_[i].get()->getSize(), rawMemSize);
auto data = reinterpret_cast<Dtype*>(dataMems_[i].get()->getBuf());
for (size_t j = 0; j < dataMemSize; ++j) {
sendData[j] += data[j];
}
}
std::vector<iovec> outputIovs;
auto block = response.add_blocks();
outputIovs.push_back({sendData, rawMemSize});
block->set_total_size(rawMemSize);
block->set_data_size(sizeof(Dtype));
callback(response, outputIovs);
}
void ParameterServer2::templateReduceSum(const SendDataRequest& request,
std::unique_ptr<MsgReader>& msgReader,
ProtoResponseCallbackEx& callback) {
const auto& block = request.blocks(0);
switch (block.data_type()) {
case TRANS_FLOAT:
reduceAndSendData<float>(request, msgReader, callback);
break;
case TRANS_DOUBLE:
reduceAndSendData<double>(request, msgReader, callback);
break;
case TRANS_INT32:
reduceAndSendData<int>(request, msgReader, callback);
break;
case TRANS_UINT32_T:
reduceAndSendData<uint32_t>(request, msgReader, callback);
break;
case TRANS_INT64_T:
reduceAndSendData<int64_t>(request, msgReader, callback);
break;
case TRANS_UINT64_T:
reduceAndSendData<uint64_t>(request, msgReader, callback);
break;
default:
LOG(FATAL) << "not supported";
break;
}
}
void ParameterServer2::sendData(const SendDataRequest& request,
std::unique_ptr<MsgReader> msgReader,
ProtoResponseCallbackEx callback) {
SendDataResponse response;
response.set_type(request.type());
response.set_server_id(serverId_);
switch (request.update_mode()) {
case DATA_UPDATE_MODE_SET_OWN: {
CHECK_EQ(msgReader->getNumBlocks(), (size_t)(request.blocks_size()));
size_t totalLen = msgReader->getTotalLength();
if (totalLen > 0) {
CHECK_EQ(msgReader->getNumBlocks(), 1U)
<< "Only one block currently support now!";
const auto& block = request.blocks(0);
if (0 == dataSize_) {
dataSize_ = block.data_size();
} else {
CHECK_EQ(dataSize_, block.data_size());
}
int64_t serverId = request.server_id();
if (serverId_ < 0) {
serverId_ = serverId;
} else {
CHECK_EQ(serverId_, serverId);
}
int64_t clientId = request.client_id();
dataMems_[clientId] = std::make_shared<CpuMemoryHandle>(totalLen);
CHECK_EQ(totalLen % sizeof(block.data_size()), 0U);
msgReader->readNextBlock(dataMems_[clientId].get()->getBuf());
}
msgReader.reset();
std::vector<iovec> outputIovs;
callback(response, outputIovs);
break;
}
case DATA_UPDATE_MODE_GET_ALL: {
/// Currently only support DATA_REDUCE_SUM
/// And their Operations are just add
CHECK(DATA_REDUCE_SUM == request.type());
templateReduceSum(request, msgReader, callback);
break;
}
default: { LOG(FATAL) << "not supported"; }
}
}
void ParameterServer2::clearUnusedSegments(CpuVector* vec) {
real* data = vec->getData();
if (usedSegments_.empty()) {
return;
}
memset(data, 0, sizeof(real) * usedSegments_[0].first);