-
Notifications
You must be signed in to change notification settings - Fork 1
/
HPBundle.py
1470 lines (1180 loc) · 52.1 KB
/
HPBundle.py
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
"""
This code contains code for hybrid parallelism (HP) bundle.
One HP_Bundle contains two worker: Front_Worker and Rear_Worker
For Data Parallelism only, worker can be used.
For more detail of its usage, please refer to main.py
- last update: 2019.10.15
- E.Jubilee Yang
"""
import torch, threading, model, math
from termcolor import colored
from bundle_worker import Front, Rear, Worker
from util import AverageMeter, ProgressMeter
import torch.multiprocessing as mp
import torch.distributed as dist
import numpy as np
import time
def _sync_collect_gradients(rank, ps, upload_q):
for i, param in enumerate(ps):
tmp = upload_q[rank].get()
ps[i] += tmp.clone().detach()
del tmp
return
def _sync_distribute_gradients(rank, ps, download_q):
for i, param in enumerate(ps):
download_q[rank].put(param)
def _sync_init_t(rank, ps, upload_q):
for i, param in enumerate(ps):
tmp = upload_q[rank].get()
ps[i] = tmp
del tmp
def _sync_init(num_worker, ps, upload_q):
ps_threads = []
for rank in range(num_worker):
t = threading.Thread(target=_sync_init_t, args=(rank, ps, upload_q))
t.start()
ps_threads.append(t)
for t in ps_threads:
t.join()
def _sync_collect_ps(num_worker, ps, upload_q):
# collect gradients
ps_threads = []
for rank in range(num_worker):
t = threading.Thread(target=_sync_collect_gradients,
args=(rank, ps, upload_q))
t.start()
ps_threads.append(t)
for t in ps_threads:
t.join()
return
def _sync_distribute_ps(num_worker, ps, download_q):
# distribute gradients over workers
ps_threads = []
for rank in range(num_worker):
t = threading.Thread(target=_sync_distribute_gradients,
args=(rank, ps, download_q))
t.start()
ps_threads.append(t)
for t in ps_threads:
t.join()
return
def _get_bundle_topology(shape):
"""
:param shape: list describing bundle shape [#fronts, #rear]
:return:
"""
topology = []
local_max_degree = torch.cuda.device_count()
total_degree = shape[0] + shape[1]
if total_degree <= local_max_degree:
topology.append(shape)
return topology
elif shape[0] >= local_max_degree:
topology.append([local_max_degree, 0])
topology += _get_bundle_topology([shape[0] - local_max_degree, shape[1]])
return topology
elif (shape[0] is not 0) and (shape[0] <= local_max_degree):
if (shape[1] > local_max_degree) and (total_degree % local_max_degree == 0):
topology.append([shape[0], local_max_degree - shape[0]])
topology += _get_bundle_topology([0, shape[1] - local_max_degree + shape[0]])
return topology
else:
topology.append([shape[0], 0])
topology += _get_bundle_topology([0, shape[1]])
return topology
elif shape[1] >= local_max_degree:
topology.append([0, local_max_degree])
topology += _get_bundle_topology([shape[0], shape[1] - local_max_degree])
return topology
def _print_error(msg, is_exit=False):
print(colored('\n-------------------- '
'ERROR MESSAGE PRINT '
'---------------------\n', "yellow"))
print(colored(' <ERROR!>', "red"),
colored(msg, 'yellow'))
print(colored('\n---------------------- '
'EXIT THE PROGRAM '
'----------------------\n', "yellow"))
if is_exit:
exit()
class HP_BUNDLE():
def __init__(self, shape, num_bundles, num_nodes, rank, args):
"""
:param shape: shape of bundle
:param num_bundles: (global) total number of bundles running in Bundle-based HP
:param num_nodes: (global) total number of nodes participating in this Bundle-based HP
:param rank: (global) rank of this node among the training cluster
:param args:
"""
self.shape = shape
self.num_bundles = num_bundles
self.num_nodes = num_nodes
self.node_rank = rank
self.args = args
self.front_worker_bs = self.args.batch_size // self.shape[0]
self.rear_worker_bs = self.args.batch_size // self.shape[1]
# Get topology information & partial_bundle or not
self._get_bundle_info()
# bundles
self.bundles = []
# MICRO BUNDLE
if self.IS_MICRO_BUNDLE:
self.local_shape = self.topology[self.local_node_rank]
rank = 0
if self.local_shape[0] is not 0:
self.front_hp_upQ = []
self.front_hp_downQ = []
batch_size = self.front_worker_bs * self.local_shape[0]
self.bundles.append(Bundle(shape=[self.local_shape[0], 0],
rank=rank,
batch_size=batch_size,
args=args))
self.front_hp_downQ.append(mp.Queue())
self.front_hp_upQ.append(mp.Queue())
self.bundles[rank].set_front_hpQ(self.front_hp_upQ[0], self.front_hp_downQ[0])
rank += 1
if self.local_shape[1] is not 0:
self.rear_hp_upQ = []
self.rear_hp_downQ = []
batch_size = self.rear_worker_bs * self.local_shape[1]
self.bundles.append(Bundle(shape=[0, self.local_shape[1]],
rank=rank,
offset=self.local_shape[0],
batch_size=batch_size,
args=args))
self.rear_hp_downQ.append(mp.Queue())
self.rear_hp_upQ.append(mp.Queue())
self.bundles[rank].set_rear_hpQ(self.rear_hp_upQ[0], self.rear_hp_downQ[0])
# monolithic bundle
else:
self.front_hp_downQ = []
self.front_hp_upQ = []
self.rear_hp_downQ = []
self.rear_hp_upQ = []
self.num_bundle_worker = self.shape[0]+self.shape[1]
for rank in range(self.local_num_hp):
self.bundles.append(Bundle(shape=self.shape,
rank=rank,
batch_size=self.batch_size,
args=args,
offset=rank * self.num_bundle_worker))
self.front_hp_downQ.append(mp.Queue())
self.front_hp_upQ.append(mp.Queue())
self.bundles[rank].set_front_hpQ(uploadQ=self.front_hp_upQ[rank],
downloadQ=self.front_hp_downQ[rank])
self.rear_hp_downQ.append(mp.Queue())
self.rear_hp_upQ.append(mp.Queue())
self.bundles[rank].set_rear_hpQ(uploadQ=self.rear_hp_upQ[rank],
downloadQ=self.rear_hp_downQ[rank])
def run(self):
processes = []
offset = 0
# micro bundle
if self.IS_MICRO_BUNDLE:
# RUN HP_PS for front
if self.local_shape[0] is not 0:
p = mp.Process(target=self._hp_micro_front_ps,
args=(offset,))
p.start()
processes.append(p)
offset += 1
# RUN HP_PS for rear
if self.local_shape[1] is not 0:
p = mp.Process(target=self._hp_micro_rear_ps,
args=(offset,))
p.start()
processes.append(p)
# RUN bundles
for bundle in self.bundles:
p = mp.Process(target=bundle.run)
p.start()
processes.append(p)
for p in processes:
p.join()
# monolithic bundle
else:
p = mp.Process(target=self._hp_front_ps)
p.start()
processes.append(p)
p = mp.Process(target=self._hp_rear_ps)
p.start()
processes.append(p)
for bundle in self.bundles:
p = mp.Process(target=bundle.run)
p.start()
processes.append(p)
for p in processes:
p.join()
def _get_bundle_info(self):
"""
bundle_degree : number of sub bundles consisting of one bundle
topology : global topology
:return:
"""
self.topology = _get_bundle_topology(self.shape)
self.bundle_degree = len(self.topology)
self.num_gpus = torch.cuda.device_count()
self.IS_MICRO_BUNDLE = False if self.bundle_degree == 1 else True
# self.local_num_hp = self.num_gpus // (self.topology[0][0] + self.topology[0][1])
if self.IS_MICRO_BUNDLE:
self.local_num_hp = 1
else:
self.local_max_num_hp = self.num_gpus // (self.topology[0][0] + self.topology[0][1])
if self.args.num_bundle > self.local_max_num_hp * self.args.world_size:
_print_error("Please check the running configuration ! \n"
"\tIn sufficient number of workers", True)
num_hp = [self.local_max_num_hp] * self.args.world_size
if self.args.num_bundle % self.local_max_num_hp is not 0:
num_hp[self.args.num_bundle // self.local_max_num_hp] = self.args.num_bundle % self.local_max_num_hp
self.local_num_hp = num_hp[self.node_rank]
if self.IS_MICRO_BUNDLE:
self._get_micro_bundle_rank()
else:
self._get_monolithic_bundle_rank()
def _get_micro_bundle_rank(self):
"""
This function returns (global_bundle_rank, local_bundle_rank, topology, IS_LOCAL_MASTER)
This function should be called in INTER_BUNDLE
"""
self.local_node_rank = self.node_rank % self.bundle_degree
self.bundle_rank = self.node_rank // self.bundle_degree
self.batch_size = self.args.batch_size // self.num_bundles
if self.IS_MICRO_BUNDLE and self.bundle_degree * self.num_bundles > self.num_nodes:
_print_error("This INTER_BUNDLE cannot run on this configuration \n" +
"\t At least %d nodes are required to run one bundle \n" % (self.bundle_degree) +
"\t Total %d gpus are required to run %d bundles" % (
self.bundle_degree * self.num_nodes, self.num_bundles), True)
if self.bundle_degree is 1:
_print_error("Use INTRA_BUNDLE instead of INTER_BUNDLE \n", True)
self.front_intra_bundle_group = []
self.rear_intra_bundle_group = []
rank = 0
for node in self.topology:
if node[0] is not 0:
self.front_intra_bundle_group.append(rank)
rank += 1
if node[1] is not 0:
self.rear_intra_bundle_group.append(self.bundle_rank * self.bundle_degree + rank)
rank += 1
# number of HP_PS is bundle offset (not bundle_degree)
# bundle degree denotes the number of worker required to run one bundle
bundle_offset = len(self.front_intra_bundle_group) + len(self.rear_intra_bundle_group)
self.front_intra_bundle_group = [i + bundle_offset * self.bundle_rank for i in self.front_intra_bundle_group]
self.rear_intra_bundle_group = [i + bundle_offset * self.bundle_rank for i in self.rear_intra_bundle_group]
self.mp_intra_bundle_group = [self.front_intra_bundle_group[0], self.rear_intra_bundle_group[0]]
self.global_sync_front_dp = [i * bundle_offset for i in range(self.args.num_bundle)]
self.global_sync_rear_dp = [i * bundle_offset + len(self.front_intra_bundle_group) for i in
range(self.args.num_bundle)]
# world_size
self.world_size = bundle_offset * self.args.num_bundle
# global rank of this micro-bundle
self.global_rank = bundle_offset * self.bundle_rank + self.local_node_rank
def _get_monolithic_bundle_rank(self):
if self.local_max_num_hp * self.num_nodes < self.num_bundles:
_print_error("Number of node is not sufficient to run this bundle", True)
elif self.node_rank > self.num_bundles // self.local_num_hp:
print(colored("<WARNING>", "yellow"),
"This node is not required in Bundle-based HP")
exit()
else:
self.world_num_nodes = math.ceil(self.num_bundles / self.local_max_num_hp)
self.world_size = self.world_num_nodes * 2
self.batch_size = self.args.batch_size // self.num_bundles
self.global_sync_front_dp = [2 * i for i in range(self.world_num_nodes)]
self.global_sync_rear_dp = [2 * i + 1 for i in range(self.world_num_nodes)]
self.front_intra_bundle_group = None
self.rear_intra_bundle_group = None
self.mp_intra_bundle_group = None
def _hp_micro_front_ps(self, rank_offset):
# Average Meter
dist_sync = AverageMeter('dist_sync', ':6.3f')
distribute_grad = AverageMeter('distribute_grad', ':6.3f')
comm_forward = AverageMeter('comm_forward', ":6.3f")
comm_backward = AverageMeter('comm_backward', ":6.3f")
comm_gather = AverageMeter('comm_gather', ":6.3f")
comm_scatter = AverageMeter('comm_scatter', ":6.3f")
bundle_sync = AverageMeter('bundle_sync', ':6.3f')
# Progress Meter
progress = ProgressMeter(self.args.itr,
'HP_FRONT',
'white',
dist_sync,
distribute_grad,
comm_forward,
comm_backward,
comm_gather,
comm_scatter,
bundle_sync)
# declare dist process
global_rank = self.global_rank + rank_offset
dist.init_process_group(backend='gloo',
init_method='tcp://%s:%s' % (self.args.IP, self.args.portNum),
rank=global_rank,
world_size=self.world_size)
self.sync_front_group = dist.new_group(self.global_sync_front_dp)
self.sync_rear_group = dist.new_group(self.global_sync_rear_dp)
# For micro bundle
self.dist_front_intra_bundle_group = dist.new_group(self.front_intra_bundle_group)
self.dist_rear_intra_bundle_group = dist.new_group(self.rear_intra_bundle_group)
self.dist_mp_intra_bundle_group = dist.new_group(self.mp_intra_bundle_group)
# front ps
self.front_ps = []
front_model = getattr(model, self.args.model + "_front")
front_model = front_model()
for layer in front_model.parameters():
self.front_ps.append(layer.grad)
# front sender & receiver
forward_mp_list = []
backprop_mp_list = []
# initialization
input = torch.tensor(np.zeros([self.front_worker_bs, 3, 224, 224], np.float32))
front_output = front_model(input)
output_shape = [-1, front_output.shape[1], front_output.shape[2], front_output.shape[3]]
bs = self.front_worker_bs * self.local_shape[0]
front_bs = self.front_worker_bs * self.topology[0][0]
backprop_shape = [front_bs] + output_shape[1:]
backprop_tmp = torch.tensor(np.zeros(backprop_shape, np.float32))
if self.local_node_rank == self.front_intra_bundle_group[0]:
for rank in self.front_intra_bundle_group:
#[2019/11/04] Currently, pyTorch does not support different size tensor gather/scatter T.T
#bs = self.front_worker_bs * self.topology[rank][0]
forward_shape = [bs] + output_shape[1:]
forward_mp_list.append(torch.tensor(np.zeros(forward_shape, np.float32)))
for itr in range(self.args.itr):
# collect feedforward for mp
feed_forward_tmp = self.front_hp_upQ[0].get()
# intra collect (dist.gather)
if len(self.front_intra_bundle_group) > 1:
# padding more data for gather
if bs < front_bs:
feed_forward_tmp = torch.cat([feed_forward_tmp, feed_forward_tmp[:(front_bs-bs)]],0)
# gather
comm_gather.tic()
dist.gather(tensor=feed_forward_tmp,
gather_list=forward_mp_list,
dst=self.front_intra_bundle_group[0],
group=self.dist_front_intra_bundle_group,
async_op=False)
comm_gather.toc()
# send feed forward to rear server
if self.local_node_rank == self.front_intra_bundle_group[0]:
# create merged feed forward tensor
merged_forward = torch.cat(forward_mp_list)
merged_forward = (merged_forward.split(self.args.batch_size))[0]
# send feed forward tensor
comm_forward.tic()
dist.send(tensor=merged_forward,
dst=self.mp_intra_bundle_group[1],
group=self.dist_mp_intra_bundle_group)
comm_forward.toc()
# distribute backprop for mp
if self.local_node_rank == self.front_intra_bundle_group[0]:
# merged backpropagation tensor
merged_backprop = torch.tensor(np.zeros(merged_forward.shape, np.float32))
# receive from the representative rear server
comm_backward.tic()
dist.recv(tensor=merged_backprop,
src=self.mp_intra_bundle_group[1],
group=self.dist_mp_intra_bundle_group)
comm_backward.toc()
# split the backpropagation tensor into tensors list
backprop_mp_list = list(torch.split(merged_backprop,
front_bs))
# scatter the split backpropagation within intra-bundle
if len(self.front_intra_bundle_group) > 1:
# check padding for scatter
for front_rank in range(len(backprop_mp_list)):
worker_bs = backprop_mp_list[front_rank].shape[0]
# add dummy data!
if worker_bs < front_bs:
backprop_mp_list[front_rank] = torch.cat([backprop_mp_list[front_rank], backprop_mp_list[front_rank-1][:(front_bs-worker_bs)]])
comm_scatter.tic()
dist.scatter(tensor=backprop_tmp,
scatter_list=backprop_mp_list,
src=self.front_intra_bundle_group[0],
group=self.dist_front_intra_bundle_group,
async_op=False)
comm_scatter.toc()
if bs < front_bs:
local_backprop_tmp = torch.split(backprop_tmp,
bs)[0]
else:
local_backprop_tmp = backprop_tmp
# send the backprop tensor to undle
self.front_hp_downQ[0].put(local_backprop_tmp)
# collect data for sync
if itr == 0:
_sync_init(num_worker=1,
ps=self.front_ps,
upload_q=self.front_hp_upQ)
else:
_sync_collect_ps(num_worker=1,
ps=self.front_ps,
upload_q=self.front_hp_upQ)
dist_sync.tic()
# intra all reduce
if len(self.front_intra_bundle_group) > 1:
for grad in self.front_ps:
dist.reduce(tensor=grad,
op=dist.ReduceOp.SUM,
dst=self.front_intra_bundle_group[0],
group=self.dist_front_intra_bundle_group)
# inter all reduce
if (len(self.global_sync_front_dp) > 1 ) and (self.local_node_rank == self.front_intra_bundle_group[0]):
for grad in self.front_ps:
dist.all_reduce(grad, op=dist.ReduceOp.SUM, group=self.sync_front_group)
# intra distribute sync
if len(self.front_intra_bundle_group) > 1:
for idx, grad in enumerate(self.front_ps):
dist.broadcast(tensor=self.front_ps[idx],
src=self.front_intra_bundle_group[0],
group=self.dist_front_intra_bundle_group)
dist_sync.toc()
# distribute data to bundle
distribute_grad.tic()
_sync_distribute_ps(num_worker=1,
ps=self.front_ps,
download_q=self.front_hp_downQ)
distribute_grad.toc()
progress.print_progress(itr+1)
# WAIT
time.sleep(5)
return
def _hp_micro_rear_ps(self, rank_offset):
# Average Meter
dist_sync = AverageMeter('dist_sync', ':6.3f')
distribute_grad = AverageMeter('distribute_grad', ':6.3f')
comm_forward = AverageMeter('comm_forward', ":6.3f")
comm_gather = AverageMeter('comm_gather', ":6.3f")
comm_scatter = AverageMeter('comm_scatter', ":6.3f")
comm_backward = AverageMeter('comm_backward', ":6.3f")
bundle_sync = AverageMeter('bundle_sync', ':6.3f')
# Progress Meter
progress = ProgressMeter(self.args.itr,
'HP_REAR',
'white',
dist_sync,
distribute_grad,
comm_forward,
comm_backward,
comm_gather,
comm_scatter,
bundle_sync)
# declare dist process
global_rank = self.global_rank + rank_offset
dist.init_process_group(backend='gloo',
init_method='tcp://%s:%s' % (self.args.IP, self.args.portNum),
rank=global_rank,
world_size=self.world_size)
self.sync_front_group = dist.new_group(self.global_sync_front_dp)
self.sync_rear_group = dist.new_group(self.global_sync_rear_dp)
# For micro bundle
self.dist_front_intra_bundle_group = dist.new_group(self.front_intra_bundle_group)
self.dist_rear_intra_bundle_group = dist.new_group(self.rear_intra_bundle_group)
self.dist_mp_intra_bundle_group = dist.new_group(self.mp_intra_bundle_group)
# rear ps
self.rear_ps = []
rear_model = getattr(model, self.args.model + "_rear")
rear_model = rear_model()
# rear parameter server
for layer in rear_model.parameters():
self.rear_ps.append(layer.grad)
# for the shape of the front model
front_model = getattr(model, self.args.model + "_front")
front_model = front_model()
# rear sender & receiver
forward_mp_list = []
backprop_mp_list = []
# initialization
local_batch_size = self.rear_worker_bs * self.local_shape[1]
input = torch.tensor(np.zeros([local_batch_size, 3, 224, 224], np.float32))
front_output = front_model(input)
rear_forward_input_tmp = torch.tensor(np.zeros(front_output.shape, np.float32))
bs = self.rear_worker_bs * self.local_shape[1]
# initialization
if global_rank == self.rear_intra_bundle_group[0]:
output_shape = [self.args.batch_size,
front_output.shape[1],
front_output.shape[2],
front_output.shape[3]]
forward_tensor = torch.tensor(np.zeros(output_shape, np.float32))
for rank in self.rear_intra_bundle_group:
#bs = self.rear_worker_bs * self.topology[rank][1]
backprop_shape = [bs] + output_shape[1:]
backprop_mp_list.append(torch.tensor(np.zeros(backprop_shape, np.float32)))
for itr in range(self.args.itr):
# get feed forward from dist for mp
if global_rank == self.rear_intra_bundle_group[0]:
# Receive forward tensors from front representative
comm_forward.tic()
dist.recv(tensor=forward_tensor,
src=self.mp_intra_bundle_group[0],
group=self.dist_mp_intra_bundle_group)
comm_forward.toc()
rear_local_bs = self.rear_worker_bs * self.local_shape[1]
forward_mp_list = list(torch.split(forward_tensor, rear_local_bs))
# distribute forward tensors to rear workers
if len(self.rear_intra_bundle_group) > 1:
comm_scatter.tic()
dist.scatter(tensor=rear_forward_input_tmp,
scatter_list=forward_mp_list,
src=self.rear_intra_bundle_group[0],
group=self.dist_rear_intra_bundle_group,
async_op=False)
comm_scatter.toc()
# send the forward tensor to Bundle
self.rear_hp_downQ[0].put(rear_forward_input_tmp)
# collect back propagation tensor for mp
back_propagation_tmp = self.rear_hp_upQ[0].get()
# intra collect (dist.gather)
if len(self.rear_intra_bundle_group) > 1:
comm_gather.tic()
dist.gather(tensor=back_propagation_tmp,
gather_list=backprop_mp_list,
dst=self.rear_intra_bundle_group[0],
group=self.dist_rear_intra_bundle_group,
async_op=False)
comm_gather.toc()
# send back propagation to front server
if global_rank == self.rear_intra_bundle_group[0]:
# create merged
merged_backprop = torch.cat(backprop_mp_list)
merged_backprop = (merged_backprop.split(self.args.batch_size))[0]
comm_backward.tic()
dist.send(tensor=merged_backprop,
dst=self.mp_intra_bundle_group[0],
group=self.dist_mp_intra_bundle_group)
comm_backward.toc()
# collect gradient data for sync
if itr == 0:
_sync_init(num_worker=1,
ps=self.rear_ps,
upload_q=self.rear_hp_upQ)
else:
_sync_collect_ps(num_worker=1,
ps=self.rear_ps,
upload_q=self.rear_hp_upQ)
dist_sync.tic()
# intra all reduce
if len(self.rear_intra_bundle_group) > 1:
for grad in self.rear_ps:
dist.reduce(grad,
op=dist.ReduceOp.SUM,
dst=self.rear_intra_bundle_group[0],
group=self.dist_rear_intra_bundle_group)
# inter all reduce
if (len(self.global_sync_rear_dp) > 1) and (self.local_node_rank == self.rear_intra_bundle_group[0]):
for grad in self.rear_ps:
dist.all_reduce(grad, op=dist.ReduceOp.SUM, group=self.sync_rear_group)
# intra distribute sync
if len(self.rear_intra_bundle_group) > 1:
for idx, grad in enumerate(self.rear_ps):
dist.broadcast(tensor=self.rear_ps[idx],
src=self.rear_intra_bundle_group[0],
group=self.dist_rear_intra_bundle_group)
dist_sync.toc()
# distribute data to bundle
distribute_grad.tic()
_sync_distribute_ps(num_worker=1,
ps=self.rear_ps,
download_q=self.rear_hp_downQ)
distribute_grad.toc()
progress.print_progress(itr+1)
# WAIT
time.sleep(5)
return
def _hp_front_ps(self):
# Average Meter
dist_sync = AverageMeter('dist_sync', ':6.3f')
distribute_grad = AverageMeter('distribute_grad', ':6.3f')
comm_mp = AverageMeter('comm_mp', ":6.3f")
# Progress Meter
progress = ProgressMeter(self.args.itr,
'HP_FRONT',
'white',
dist_sync,
distribute_grad,
comm_mp)
# declare dist process
rank = self.args.rank * 2
dist.init_process_group(backend='gloo',
init_method='tcp://%s:%s' % (self.args.IP, self.args.portNum),
rank=rank,
world_size=self.world_size)
self.sync_front_group = dist.new_group(self.global_sync_front_dp)
self.sync_rear_group = dist.new_group(self.global_sync_rear_dp)
# set front_ps & rear_ps
self.front_ps = []
front_model = getattr(model, self.args.model + "_front")
front_model = front_model()
for layer in front_model.parameters():
self.front_ps.append(layer.grad)
for itr in range(self.args.itr):
# collect data from
if itr == 0:
_sync_init(num_worker=self.local_num_hp,
ps=self.front_ps,
upload_q=self.front_hp_upQ)
else:
_sync_collect_ps(num_worker=self.local_num_hp,
ps=self.front_ps,
upload_q=self.front_hp_upQ)
dist_sync.tic()
if len(self.global_sync_front_dp) > 1:
for grad in self.front_ps:
dist.all_reduce(grad, op=dist.ReduceOp.SUM, group=self.sync_front_group)
dist_sync.toc()
# distribute data to bundle p
distribute_grad.tic()
_sync_distribute_ps(num_worker=self.local_num_hp,
ps=self.front_ps,
download_q=self.front_hp_downQ)
distribute_grad.toc()
progress.print_progress(itr+1)
# WAIT
time.sleep(5)
return
def _hp_rear_ps(self):
# Average Meter
dist_sync = AverageMeter('dist_sync', ':6.3f')
distribute_grad = AverageMeter('distribute_grad', ':6.3f')
comm_mp = AverageMeter('comm_mp', ":6.3f")
# Progress Meter
progress = ProgressMeter(self.args.itr,
'HP_REAR',
'white',
dist_sync,
distribute_grad,
comm_mp)
# declare dist process
rank = self.args.rank * 2 + 1
dist.init_process_group(backend='gloo',
init_method='tcp://%s:%s' % (self.args.IP, self.args.portNum),
rank=rank,
world_size=self.world_size)
self.sync_front_group = dist.new_group([2 * i for i in range(self.world_num_nodes)])
self.sync_rear_group = dist.new_group([2 * i + 1 for i in range(self.world_num_nodes)])
# set front_ps & rear_ps
self.rear_ps = []
rear_model = getattr(model, self.args.model + "_rear")
rear_model = rear_model()
for layer in rear_model.parameters():
self.rear_ps.append(layer.grad)
for itr in range(self.args.itr):
# collect data from
if itr == 0:
_sync_init(num_worker=self.local_num_hp,
ps=self.rear_ps,
upload_q=self.rear_hp_upQ)
else:
_sync_collect_ps(num_worker=self.local_num_hp,
ps=self.rear_ps,
upload_q=self.rear_hp_upQ)
dist_sync.tic()
if len(self.global_sync_rear_dp) > 1:
for grad in self.rear_ps:
dist.all_reduce(grad, op=dist.ReduceOp.SUM, group=self.sync_rear_group)
dist_sync.toc()
# distribute data to bundle p
distribute_grad.tic()
_sync_distribute_ps(num_worker=self.local_num_hp,
ps=self.rear_ps,
download_q=self.rear_hp_downQ)
distribute_grad.toc()
progress.print_progress(itr+1)
# WAIT
time.sleep(5)
return
class Bundle():
"""
Bundle objects are crated
only when all gpus are fit in the bundle size.
i.e., there is no inter model parallelism.
"""
def __init__(self, shape, rank, batch_size, args, offset=0):
self.front_worker = []
self.rear_worker = []
# bundle rank
self.rank = rank
# front worker
if shape[0] is not 0:
front_bs = batch_size // shape[0]
for i in range(shape[0]):
self.front_worker.append(Front(rank=offset + i,
batch_size=front_bs,
args=args))
offset += shape[0]
# rear worker
if shape[1] is not 0:
rear_bs = batch_size // shape[1]
for j in range(shape[1]):
self.rear_worker.append(Rear(rank=offset + j,
batch_size=rear_bs,
args=args))
self.ps = BundlePS(shape, batch_size, args)
# set parameter server Q
for rank, w in enumerate(self.front_worker):
upQ, downQ = w.get_syncQ()
self.ps.set_front_psQ(upQ, downQ, rank)
for rank, w in enumerate(self.rear_worker):
upQ, downQ = w.get_syncQ()
self.ps.set_rear_psQ(upQ, downQ, rank)
def set_front_hpQ(self, uploadQ, downloadQ):
"""
only for monolithic Bundle
:param uploadQ:
:param downloadQ:
:return:
"""
self.ps.set_front_hpQ(uploadQ, downloadQ)
def set_rear_hpQ(self, uploadQ, downloadQ):
"""
only for monolithic Bundle
:param uploadQ:
:param downloadQ:
:return:
"""
self.ps.set_rear_hpQ(uploadQ, downloadQ)
def run(self):
processes = []
p = mp.Process(target=self.ps.run)
p.start()
processes.append(p)
for w in self.front_worker:
p = mp.Process(target=w.run)
p.start()
processes.append(p)
for w in self.rear_worker:
p = mp.Process(target=w.run)
p.start()
processes.append(p)
for p in processes:
p.join()
class BundlePS():
"""
Bundle Parameter Server
- gathers front inference to send them to rear workers.
- scatters front inference to rear workers
- gathers rear backpropagation to send them to front workers.
- scatters rear backpropagation to front workers
- synchronize all gradients
"""
def __init__(self, shape, batch_size, args):
self.shape = shape
self.bs = batch_size
self.args = args
# IS_MP is True only when Intra Bundle (for Inter Bundle, mp shape should be sublated
self.IS_MP = False if (np.prod(shape) == 0) else True
self.run = self._monolithic_ps_run if self.IS_MP else self._micro_ps_run
self.init = self._monolithic_ps_init if self.IS_MP else self._micro_ps_init
self.init()
def _micro_ps_run(self):
# Micro-ps manages front workers or rear workers only.
if self.shape[1] == 0:
front_ps = mp.Process(target=self._micro_front_ps)
front_ps.start()
front_ps.join()
if self.shape[0] == 0:
rear_ps = mp.Process(target=self._micro_rear_ps)
rear_ps.start()
rear_ps.join()
def _monolithic_ps_run(self):
ps = []
front_ps = mp.Process(target=self._front_ps)
front_ps.start()
ps.append(front_ps)
rear_ps = mp.Process(target=self._rear_ps)
rear_ps.start()
ps.append(rear_ps)
for p in ps:
p.join()
def _micro_front_ps(self):
for itr in range(self.args.itr):
self._micro_mp_front_feedforward()
self._micro_mp_front_backprop()
# sync
if itr == 0:
_sync_init(num_worker=self.shape[0],
ps=self.front_ps,
upload_q=self.front_ps_uploadQ)
else:
# collect grads
_sync_collect_ps(num_worker=self.shape[0],
ps=self.front_ps,
upload_q=self.front_ps_uploadQ)
self._sync_ps(num_worker=self.shape[0],
ps=self.front_ps,
hp_upload_q=self.front_upload_hpQ,
hp_download_q=self.front_download_hpQ)
# distribute graidnets
_sync_distribute_ps(num_worker=self.shape[0],
ps=self.front_ps,
download_q=self.front_ps_downQ)
# WAIT
time.sleep(1)
return
def _micro_rear_ps(self):