forked from DeepPoolML/DeepPool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallelizationPlanner.py
1951 lines (1700 loc) · 107 KB
/
parallelizationPlanner.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
# Copyright (c) 2021 MIT
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
# from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.autograd import Variable
import time
import collections
from typing import Type, Any, Callable, Union, List, Optional
from torch.nn.common_types import _size_1_t, _size_2_t, _size_3_t
import math
import jsonpickle
import json
import numpy
import graphviz
from array import array
from typing import Optional, IO, List, Any
from gpuProfiler import GpuProfiler
from jobDescription import TrainingJob
from jobDescription import Layer
import torch.cuda.profiler as profiler
import torch.cuda.nvtx as nvtx
import random
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
class SearchContext:
def __init__(self, totalGpus: int, globalBatch: int, amplificationLimit: float = 2.0,
dataParallelBaseline = False, sampleSplit=True, spatialSplit=False, filterSplit=False,
doNotBench = False):
self.totalGpus = totalGpus
self.globalBatch = globalBatch
self.amplificationLimit = amplificationLimit
self.dataParallelBaseline = dataParallelBaseline
self.sampleSplit = sampleSplit
self.spatialSplit = spatialSplit
self.filterSplit = filterSplit
self.doNotBench = doNotBench
print("SearchContext: " + str(self.__dict__))
class CostSim:
def __init__(self, profiler: GpuProfiler = None, netBw = 2.66E5, verbose=False, gpuProfileLoc=None, gpuProfileLocSub=None):
self.profiler = profiler
self.layers: List[Layer] = []
self.NET_BANDWIDTH = netBw
self.NET_LATENCY = 40
# self.NET_LATENCY = 400 #40
self.verbose = verbose
self.autocast = True
def setAutocast(self, autocast):
self.autocast = autocast
def setLossFunction(self, lossfn):
self.layers[-1].losslayer = lossfn
def queryLayerProfileCache(self, layer, config: tuple):
return sum(self.queryFwBwTime(layer, config))
def queryFwBwTime(self, layer, config: tuple):
p = GpuProfiler("cuda")
return p.queryFwBwTime(layer, config, self.autocast)
def generateModuleDescription(self, layerConfigs: list, globalBatch: int):
# gpuTimeSum = 0
# profiler.start()
maxGpuUsed = 0
for l, config in zip(self.layers, layerConfigs):
maxGpuUsed = max(maxGpuUsed, self.calcGpusNeeded(l, config, globalBatch))
# nvtx.range_push("l %d %s" % (l.id, l.name))
# gpuTime = self.benchGpuTime(l, config, profile=True)
# gpuTime = self.benchGpuTime(l, config)
# nvtx.range_pop()
# gpuTimeSum += gpuTime
# print("gpuTimeSum: ", gpuTimeSum)
# profiler.stop()
return TrainingJob("test", self.layers, layerConfigs, globalBatch, maxGpuUsed, "na")
# job.dumpSingleRunnableModule(15)
def printAllLayers(self, silent=False):
#TODO: topological sort of layers. Right now, assume it's sorted.
for i in range(len(self.layers)):
self.layers[i].id = i
for i in range(len(self.layers)):
layer = self.layers[i]
# layer.id = i
prevLayerIds = []
if layer.prevLayers != None:
for prevLayer in layer.prevLayers:
prevLayerIds.append(prevLayer.id)
nextLayerIds = []
for l in layer.nextLayers:
nextLayerIds.append(l.id)
if silent == False:
print("%3d %12s %20s %20s %s" % (i, layer.name, str(prevLayerIds), str(nextLayerIds), str(layer.params)) )
def computeInputDimensions(self, inputDim, dtype=torch.float32):
self.layers[0].setInputShapes([torch.zeros(inputDim, dtype=dtype)])
for l in self.layers:
l.getOutputShape()
def calcInputXfer(self, srcLayer: Layer, destLayer: Layer, srcConfig: tuple, destConfig: tuple, noGpuOverlap = False):
namesIn2d = ["conv2d", "maxPool2d", "avgPool2d", "adAvgPool2d", "ReLU2d", "concat"]
namesIn1d = ["linear", "ReLU1d"]
# Don't allow dynamic scaling from real layers to relu.
reluMultiple = 1
if destLayer.name in ["ReLU2d", "ReLU1d", "flatten", "BatchNorm2d"]:
reluMultiple = 1000
if srcLayer.name in namesIn2d and \
destLayer.name in namesIn2d + ["flatten"]:
actTime = self.calc2dActivationTime(srcLayer, destLayer, srcConfig, destConfig, noGpuOverlap)
return (actTime[0] * reluMultiple, actTime[1])
elif srcLayer.name in namesIn1d + ["flatten"] and \
destLayer.name in namesIn1d:
actTime = self.calcLinearActivationTime(srcLayer, destLayer, srcConfig, destConfig, noGpuOverlap)
return (actTime[0] * reluMultiple, actTime[1])
else:
actTime = self.calcGeneralActivationTime(srcLayer, destLayer, srcConfig, destConfig, noGpuOverlap)
return (actTime[0] * reluMultiple, actTime[1])
# print("Can't compute input transfer time from %s to %s." % (srcLayer.name, destLayer.name))
def calcSyncTime(self, layer, config, ctx):
if layer.name in ["conv2d"]:
syncTime = self.calcConv2dSyncTime(layer, config)
elif layer.name in ["linear"]:
syncTime = self.calcLinearSyncTime(config, ctx.globalBatch)
else:
syncTime = 0
return syncTime
def calcConv2dSyncTime(self, layer, config, bytesPerParam=4):
filterCount = config[4]
kernelSizeW = layer.params["kernel_size"][0] if type(layer.params["kernel_size"]) is tuple else layer.params["kernel_size"]
kernelSizeH = layer.params["kernel_size"][1] if type(layer.params["kernel_size"]) is tuple else 1
params = kernelSizeW * kernelSizeH * filterCount + kernelSizeW * kernelSizeH
size = params * bytesPerParam
return size / self.NET_BANDWIDTH # Returns microseconds.
def calc2dActivationTime(self, srcLayer: Layer, destLayer: Layer, srcConfig: tuple, destConfig: tuple, noGpuOverlap = False):
bytesPerParam = 4
# Compute output dimension of previous and current layer.
srcS = srcConfig[0]
srcW = srcConfig[1] * srcLayer.outputDim[1] // srcLayer.inputDim[1] # Adjusts based on input/output ratio.
srcH = srcConfig[2] * srcLayer.outputDim[2] // srcLayer.inputDim[2] # It's necessary for pool or conv2d with stride > 1
srcOutChannel = srcConfig[4] if len(srcConfig) >= 5 else srcConfig[3] # non-convolutional 2d layers don't have filter.
destS = destConfig[0]
destW = destConfig[1]
destH = destConfig[2]
# destInChannel = destConfig[3]
destInChannel = srcOutChannel # TODO: temporary hack to handle Inception V3's concat.
srcNoIndependent = True
destNoIndependent = True
if hasattr(srcLayer, 'gpuAssignment') and hasattr(destLayer, 'gpuAssignment'):
for r in srcLayer.gpuAssignment:
if r not in destLayer.gpuAssignment:
srcNoIndependent = False
break
for r in destLayer.gpuAssignment:
if r not in srcLayer.gpuAssignment:
destNoIndependent = False
break
else:
# Compute "estimated" number of gpus used for src and dest. This is used only for comparing which side might unshared gpus.
srcGpus = self.calcGpusNeeded(srcLayer, srcConfig, srcS * destS)
destGpus = self.calcGpusNeeded(destLayer, destConfig, srcS * destS)
if srcGpus > destGpus:
srcNoIndependent = False # no src node is stopped used in dest.
if srcGpus < destGpus:
destNoIndependent = False # no dest node is newly used.
# Compute common part that doesn't have to move.
commonSize = bytesPerParam * min(srcS, destS) * min(srcW, destW) * min(srcH, destH) * min(srcOutChannel, destInChannel)
if noGpuOverlap:
commonSize = 0
# Halo exchange
if "kernel_size" in destLayer.params: # TODO: hack for adaptive avgPool2D.
if type(destLayer.params["kernel_size"]) is tuple:
haloW = int((destLayer.params["kernel_size"][0] - 1) / 2)
haloH = int((destLayer.params["kernel_size"][1] - 1) / 2)
else:
haloW = int((destLayer.params["kernel_size"] - 1) / 2)
haloH = int((destLayer.params["kernel_size"] - 1) / 2)
else:
haloW = 0
haloH = 0
haloPixels = 2 * haloW * ((destH + haloH) if destW != destLayer.inputDim[1] else 0)\
+ 2 * haloH * ((destW + haloW) if destH != destLayer.inputDim[2] else 0)
haloSize = bytesPerParam * min(srcS, destS) * haloPixels * min(srcOutChannel, destInChannel)
# compute times
egressBytes = bytesPerParam * srcS * srcW * srcH * srcOutChannel + (haloSize - commonSize) if srcNoIndependent else bytesPerParam * srcS * srcW * srcH * srcOutChannel + haloSize
ingressBytes = bytesPerParam * destS * destW * destH * destInChannel + (haloSize - commonSize) if destNoIndependent else bytesPerParam * destS * destW * destH * destInChannel + haloSize
activationTime = max(egressBytes, ingressBytes) / self.NET_BANDWIDTH
activationTime += self.NET_LATENCY if activationTime > 0 else 0
return (2 * activationTime, (egressBytes, ingressBytes, haloSize)) # double to count both forward and backward passes.
def calcLinearSyncTime(self, config, globalBatch, bytesPerParam=4, alwaysPaySyncTime=False):
if not alwaysPaySyncTime and config[0] == globalBatch: # No split.
return 0
inFeatures = config[1]
outFeatures = config[2]
params = inFeatures * outFeatures + outFeatures
size = params * bytesPerParam
return size / self.NET_BANDWIDTH # Returns microseconds.
def calcLinearActivationTime(self, srcLayer: Layer, destLayer: Layer, srcConfig: tuple, destConfig: tuple, noGpuOverlap: bool):
bytesPerParam = 4
# Prepare variables.
prevOutFeatures = 0
if len(srcConfig) >= 4: # prev layer was conv2d.
# print("%s to %s" % (srcLayer.name, destLayer.name))
srcS = srcConfig[0]
srcW = srcConfig[1] * 1 if srcLayer.name == "flatten" else (srcLayer.outputDim[1] // srcLayer.inputDim[1]) # Adjusts based on input/output ratio.
srcH = srcConfig[2] * 1 if srcLayer.name == "flatten" else (srcLayer.outputDim[2] // srcLayer.inputDim[2]) # It's necessary for pool or conv2d with stride > 1
srcOutChannel = srcConfig[4] if len(srcConfig) >= 5 else srcConfig[3] # non-convolutional 2d layers don't have filter.
srcOutFeatures = srcW * srcH * srcOutChannel
splitFactor = 1
elif len(srcConfig) == 3:
srcS = srcConfig[0]
srcOutFeatures = srcConfig[2]
splitFactor = srcLayer.inputDim / srcConfig[1] # This much output must be added up to get the final output.
else:
print("[calcLinearActivationTime] error! srcConfig dimensions is not correct.")
destS = destConfig[0]
destInFeatures = destConfig[1]
commonSize = bytesPerParam * min(srcS, destS) * min(srcOutFeatures, destInFeatures)
if noGpuOverlap:
commonSize = 0
# compute times
egressBytes = bytesPerParam * srcS * srcOutFeatures * splitFactor - commonSize
ingressBytes = bytesPerParam * destS * destInFeatures * splitFactor - commonSize
activationTime = max(egressBytes, ingressBytes) / self.NET_BANDWIDTH
activationTime += self.NET_LATENCY if activationTime > 0 else 0
# print("activationTime:%.1f, egressBytes:%d, ingressBytes:%d, splitFactor: %d, commonSize: %d" %\
# (activationTime, egressBytes, ingressBytes, splitFactor, commonSize))
return (2 * activationTime, (egressBytes, ingressBytes, splitFactor)) # double to count both forward and backward passes.
def calcGeneralActivationTime(self, srcLayer: Layer, destLayer: Layer, srcConfig: tuple, destConfig: tuple, noGpuOverlap: bool):
# print("srcConfig: ", srcConfig)
bytesPerParam = 4
# Prepare variables.
srcS = srcConfig[0]
srcOutFeatures = numpy.prod(srcLayer.outputDim)
destS = destConfig[0]
destInFeatures = numpy.prod(destLayer.inputDim)
splitFactor = 1
commonSize = bytesPerParam * min(srcS, destS) * min(srcOutFeatures, destInFeatures)
if noGpuOverlap:
commonSize = 0
# compute times
egressBytes = bytesPerParam * srcS * srcOutFeatures * splitFactor - commonSize
ingressBytes = bytesPerParam * destS * destInFeatures * splitFactor - commonSize
activationTime = max(egressBytes, ingressBytes) / self.NET_BANDWIDTH
activationTime += self.NET_LATENCY if activationTime > 0 else 0
# print("activationTime:%.1f, egressBytes:%d, ingressBytes:%d, splitFactor: %d, commonSize: %d" %\
# (activationTime, egressBytes, ingressBytes, splitFactor, commonSize))
return (2 * activationTime, (egressBytes, ingressBytes, splitFactor)) # double to count both forward and backward passes.
def Conv2d(self,
in_channels: int,
out_channels: int,
kernel_size,
stride: _size_2_t = 1,
padding: _size_2_t = 0,
dilation: _size_2_t = 1,
groups: int = 1,
bias: bool = True,
padding_mode: str = 'zeros',
custom_previous_layers: list = None):
module = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "conv2d",
{"in_channels": in_channels, "out_channels": out_channels, "kernel_size": kernel_size, "stride": stride, "padding": padding},
prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def MaxPool2d(self,
kernel_size: _size_2_t,
stride: _size_2_t,
padding: _size_2_t = 0,
# dilation: _size_2_t = 1,
custom_previous_layers: list = None):
module = nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=padding) #, dilation=dilation)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "maxPool2d",
{"kernel_size": kernel_size, "stride": stride, "padding": padding},
prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def AdaptiveAvgPool2d(self,
output_size,
custom_previous_layers: list = None):
module = nn.AdaptiveAvgPool2d(output_size)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
# stride = (input_size//output_size)
# kernel_size = input_size - (output_size-1)*stride
# padding = 0
layer = Layer(module, "adAvgPool2d",
{"output_width": output_size[0], "output_height": output_size[1]},
prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def AvgPool2d(self, kernel_size: _size_2_t, stride: Optional[_size_2_t] = None, padding: _size_2_t = 0,
ceil_mode: bool = False, count_include_pad: bool = True, divisor_override: bool = None,
custom_previous_layers: list = None):
module = nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding, ceil_mode=ceil_mode,
count_include_pad=count_include_pad, divisor_override=divisor_override)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "avgPool2d",
{"kernel_size": kernel_size, "stride": stride, "padding": padding},
prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def Linear(self, in_features: int, out_features: int, bias: bool = True, custom_previous_layers: list = None):
module = nn.Linear(in_features, out_features, bias)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "linear",
{"in_features": in_features, "out_features": out_features, "bias": bias},
prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def ReLU(self, inplace: bool = False, custom_previous_layers: list = None):
module = nn.ReLU(inplace=inplace)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
if custom_previous_layers[0].name in ["conv2d", "maxPool2d", "avgPool2d", "adAvgPool2d", "concat"]:
name = "ReLU2d"
elif custom_previous_layers[0].name in ["linear"]:
name = "ReLU1d"
else:
name = "ReLU"
layer = Layer(module, name, {"inplace": inplace, "kernel_size": 1, "stride": 1, "padding": 0}, prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def Flatten(self, custom_previous_layers: list = None):
module = nn.Flatten(start_dim=1)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "flatten", {"kernel_size": 1}, prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
class ConcatInputs(nn.Module):
def __init__(self, dim: int = 1):
super(CostSim.ConcatInputs, self).__init__()
self.dim = dim
def forward(self, *inputList: List[torch.Tensor]):
out = torch.cat(inputList, dim=self.dim)
return out
def Concat(self, custom_previous_layers: list = None): # concatenates tensors on channel dimension only.
module = CostSim.ConcatInputs(dim=1)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "concat", {"kernel_size": 1}, prevLayers = custom_previous_layers)
layer.must_trace = True
self.layers.append(layer)
return
def Dropout(self, dropout = 0.5, inplace: bool = False, custom_previous_layers: list = None):
module = nn.Dropout(dropout, inplace=inplace)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "dropout", {"dropout": dropout}, prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def LayerNorm(self, dim, custom_previous_layers: list = None):
module = nn.LayerNorm(dim)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "layerNorm", {"dim": dim}, prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def BatchNorm2d(self, out_channels, eps=0.001, custom_previous_layers: list = None):
module = nn.BatchNorm2d(out_channels, eps=0.001)
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, "BatchNorm2d", {"out_channels": out_channels, "eps": 0.001}, prevLayers = custom_previous_layers)
self.layers.append(layer)
return module
def GeneralLayer(self, module, name, params, custom_previous_layers: list = None, mustTrace=False):
if custom_previous_layers == None and len(self.layers) > 0:
custom_previous_layers = [self.layers[-1]]
layer = Layer(module, name, params, prevLayers = custom_previous_layers)
layer.must_trace = mustTrace
self.layers.append(layer)
return layer
def listConfigOptions(self, layer, globalBatch: int, totalGpus: int, samplePo2=True, sampleSplit=True, spatialSplit=True, filterSplit=False, pruneHeuristics=False, dataParallelBaseline=False):
initCfg = layer.getInitialConfig(globalBatch)
totalSplits = int(math.log(totalGpus, 2))
# generate config candidates.
sampleSplitOptions = range(totalSplits + 1) if sampleSplit else [0]
if dataParallelBaseline:
sampleSplitOptions = [totalSplits]
if layer.name in ["conv2d"]:
configCandidates = [(int(initCfg[0] / 2**bs), math.ceil(initCfg[1] / 2**int(whs/2)), math.ceil(initCfg[1] / 2**int(whs/2+0.5)), initCfg[3], math.ceil(initCfg[4] / 2**fs) )
for bs in sampleSplitOptions \
for whs in (range(totalSplits - bs + 1) if spatialSplit else [0]) \
for fs in (range(totalSplits - bs - whs + 1) if filterSplit else [0]) ]
elif layer.name in ["linear", "ReLU1d"]:
configCandidates = [(int(initCfg[0] / 2**bs), int(initCfg[1] / 2**ins), int(initCfg[2] / 2**outs) )
for bs in sampleSplitOptions \
for ins in (range(totalSplits - bs + 1) if filterSplit else [0]) \
for outs in (range(totalSplits - bs - ins + 1) if filterSplit else [0]) ]
elif layer.name in ["flatten", "maxPool2d", "avgPool2d", "adAvgPool2d", "ReLU2d", "concat"]:
configCandidates = [(int(initCfg[0] / 2**bs), math.ceil(initCfg[1] / 2**int(whs/2)), math.ceil(initCfg[1] / 2**int(whs/2+0.5)), initCfg[3] )
for bs in sampleSplitOptions \
for whs in (range(totalSplits - bs + 1) if spatialSplit else [0]) ]
else:
configCandidates = [(int(initCfg[0] / 2**bs), *initCfg[1:] )
for bs in sampleSplitOptions ]
# if layer.name in ["conv2d"]:
# configCandidates = [(math.ceil(initCfg[0] / replicas), math.ceil(initCfg[1] / 2**int(whs/2)), math.ceil(initCfg[1] / 2**int(whs/2+0.5)), initCfg[3], math.ceil(initCfg[4] / 2**fs) )
# for whs in (range(totalSplits + 1) if spatialSplit else [0]) \
# for fs in (range(totalSplits - whs + 1) if filterSplit else [0]) \
# for replicas in (([2**ss for ss in range(totalSplits - whs - fs + 1)] if samplePo2 else range(1, 2**(totalSplits - whs - fs) + 1)) if sampleSplit else [1]) ]
# elif layer.name in ["linear", "ReLU1d"]:
# configCandidates = [(math.ceil(initCfg[0] / replicas), math.ceil(initCfg[1] / 2**ins), math.ceil(initCfg[2] / 2**outs) )
# for ins in (range(totalSplits + 1) if filterSplit else [0]) \
# for outs in (range(totalSplits - ins + 1) if filterSplit else [0]) \
# for replicas in (([2**ss for ss in range(totalSplits - ins - outs + 1)] if samplePo2 else range(1, 2**(totalSplits - ins - outs) + 1)) if sampleSplit else [1]) ]
# # for replicas in (range(1, 2**(totalSplits - ins - outs) + 1) if sampleSplit else [1]) ]
# elif layer.name in ["flatten", "maxPool2d", "avgPool2d", "adAvgPool2d", "ReLU2d", "concat"]:
# configCandidates = [(math.ceil(initCfg[0] / replicas), math.ceil(initCfg[1] / 2**int(whs/2)), math.ceil(initCfg[1] / 2**int(whs/2+0.5)), initCfg[3] )
# for whs in (range(totalSplits + 1) if spatialSplit else [0]) \
# for replicas in (([2**ss for ss in range(totalSplits - whs + 1)] if samplePo2 else range(1, 2**(totalSplits - whs) + 1)) if sampleSplit else [1]) ]
validConfigs = []
for config in configCandidates:
invalidConfig = False
for dim in range(len(config)):
if config[dim] < 1:
invalidConfig = True
break
# add some other rules..
if not invalidConfig:
validConfigs.append(config)
if pruneHeuristics:
bestGpuTimeByGpusUsed = {}
prunedConfigs = []
for config in validConfigs:
gpuCount = self.calcGpusNeeded(layer, config, globalBatch)
if gpuCount not in bestGpuTimeByGpusUsed:
bestGpuTimeByGpusUsed[gpuCount] = 999999999
gpuTime = self.benchGpuTime(layer, config)
if bestGpuTimeByGpusUsed[gpuCount] > gpuTime:
bestGpuTimeByGpusUsed[gpuCount] = gpuTime
for config in validConfigs:
gpuCount = self.calcGpusNeeded(layer, config, globalBatch)
gpuTime = self.benchGpuTime(layer, config)
if gpuTime <= bestGpuTimeByGpusUsed[gpuCount] * 1.5:
prunedConfigs.append(config)
validConfigs = prunedConfigs
return validConfigs
def displayConfigSizeGrowth(self, layer, maxNumGpus):
options = [(True, True, True), (True, True, False), (True, False, False)]
totalSplits = int(math.log(maxNumGpus, 2))
globalBatch = maxNumGpus * 4
for sampleSplit, spatialSplit, filterSplit in options:
print("Gpus Sample Spatial filter configListSize prunedConfigs")
for allowedSplits in range(totalSplits+1):
totalGpus = 2 ** allowedSplits
configs = self.listConfigOptions(layer, globalBatch, totalGpus, sampleSplit=sampleSplit, spatialSplit=spatialSplit, filterSplit=filterSplit)
prunedConfigs = self.listConfigOptions(layer, globalBatch, totalGpus, sampleSplit=sampleSplit, spatialSplit=spatialSplit, filterSplit=filterSplit, pruneHeuristics=True)
print( "%3d %5s %5s %5s : %11d %11d" % (totalGpus, str(sampleSplit), str(spatialSplit), str(filterSplit), len(configs), len(prunedConfigs) ))
def calcGpusNeeded(self, layer, config: tuple, globalBatch: int):
initCfg = layer.getInitialConfig(globalBatch)
gpuCount = 1
# if len(config) != len(initCfg):
# print("[calcGpusNeeded] dimension of configs doesn't match!! %20s layer len(config):%d != len(initCfg):%d" % (layer.name, len(config), len(initCfg)))
for i in range(len(initCfg)):
gpuCount *= int(initCfg[i] / config[i])
return gpuCount
def isConfigDataParallelOnly(self, layer, config: tuple, globalBatch: int):
initCfg = layer.getInitialConfig(globalBatch)
dpOnly = True
for i in range(1, len(config)):
if config[i] != initCfg[i]:
dpOnly = False
return dpOnly
def benchGpuTime(self, layer, config: tuple, profile=False, ctx=None):
cached = self.queryLayerProfileCache(layer, config)
if cached > 0:
return cached
else:
return 1
# This is a hack for quickly generating a plan for initial layer profiling.
if ctx != None and ctx.doNotBench:
assert ctx.totalGpus == 1
return 1
assert False, "need new profiler"
if layer.name in ["conv2d"]:
gpuTime = self.profiler.runConv2dBench(config, layer.params, profile)
print(" Something bad happened!! Missed queryLayerProfileCache")
elif layer.name in ["linear"]:
gpuTime = self.profiler.runLinearBench(config, profile)
print(" Something bad happened!! Missed queryLayerProfileCache")
else:
gpuTime = 0
return gpuTime
def runMultiChainZhihao(self, startLayer, startConfig, globalBatch: int, totalGpus: int):
k = len(startLayer.nextLayers)
llist = [[startLayer] for j in range(k)]
endLayer = None
for j in range(k):
l = startLayer.nextLayers[j]
while len(l.prevLayers) == 1: # Until join happens.
llist[j].append(l)
if len(l.nextLayers) > 1:
print("[searchMultiChain] ERROR! nested multi-chain. TODO; implement handling of this.")
l = l.nextLayers[0]
if endLayer == None:
endLayer = l
else:
assert(endLayer == l)
print("Found %d chains, branching at %d-th layer, joining at %d-th layer" % (k, startLayer.id, endLayer.id))
noParallelTimeSum = 0
t = [[ [] for i in range(len(llist[j])) ] for j in range(k)] # [layer] = list of (config, cumulativeTime, prevConfigIndex)
for branchIdx in range(k):
length = len(llist[branchIdx])
bestConfigList = []
bestTimeList = []
bestDataParallelTimeList = []
for idx in range(length):
layer = llist[branchIdx][idx]
initCfg = layer.getInitialConfig(globalBatch)
bestTime = self.benchGpuTime(layer, initCfg)
bestDataParallelTime = bestTime
noParallelTimeSum += bestTime
bestConfig = initCfg
for config in (self.listConfigOptions(layer, globalBatch, totalGpus) if idx > 0 else [startConfig]):
gpuTime = self.benchGpuTime(layer, config)
# Computer all-reduce time
# if layer.name in ["conv2d"]:
# syncTime = self.calcConv2dSyncTime(config)
# elif layer.name in ["linear"]:
# syncTime = self.calcLinearSyncTime(config, globalBatch)
# else:
# syncTime = 0
syncTime = 0
if idx == 0:
t[branchIdx][idx].append((config, syncTime, None, (0, 0, 0, syncTime, (0)) ))
else:
bestPrevCfgIdx = 0
bestCumulativeTime = 99999999999
bestTimeComposition = None
# WARNING!! Following main branch only!!
prevLayer = layer.prevLayers[0]
for prevCfgIdx in range(len(t[branchIdx][idx-1])):
prevCfg, cumulativeTime, prevConfigIndexOfPrev, timeComposition = t[branchIdx][idx-1][prevCfgIdx]
activationTime, activationSizeMatrix = self.calcInputXfer(prevLayer, layer, prevCfg, config)
newTime = cumulativeTime + activationTime + gpuTime + syncTime
if newTime < bestCumulativeTime:
bestCumulativeTime = newTime
bestTimeComposition = (cumulativeTime, activationTime, gpuTime, syncTime, activationSizeMatrix)
bestPrevCfgIdx = prevCfgIdx
t[branchIdx][idx].append((config, bestCumulativeTime, bestPrevCfgIdx, bestTimeComposition ))
if gpuTime < bestTime:
bestTime = gpuTime
bestConfig = config
bestConfigList.append(bestConfig)
bestTimeList.append(bestTime)
bestDataParallelTimeList.append(bestDataParallelTime)
# join at the endLayer. Sum up all times of all branches.
configToTimeDict = {}
for endConfig in self.listConfigOptions(endLayer, globalBatch, totalGpus):
gpuTime = self.benchGpuTime(endLayer, endConfig)
bestTime = 9999999999999
optionWithBestTime = []
sumOfBestTime = 0
for branchIdx in range(k):
bestPrevCfgIdx = 0
bestCumulativeTime = 99999999999
bestTimeComposition = None
prevLayer = llist[branchIdx][-1]
for prevCfgIdx in range(len(t[branchIdx][-1])):
prevCfg, cumulativeTime, prevConfigIndexOfPrev, timeComposition = t[branchIdx][-1][prevCfgIdx]
activationTime, activationSizeMatrix = self.calcInputXfer(prevLayer, endLayer, prevCfg, endConfig)
newTime = cumulativeTime + activationTime + gpuTime + syncTime
if newTime < bestCumulativeTime:
bestCumulativeTime = newTime
bestTimeComposition = (cumulativeTime, activationTime, gpuTime, syncTime, activationSizeMatrix)
bestPrevCfgIdx = prevCfgIdx
sumOfBestTime += bestCumulativeTime
optionWithBestTime.append(bestPrevCfgIdx)
configToTimeDict[endConfig] = (sumOfBestTime, tuple(optionWithBestTime))
return (endLayer, configToTimeDict, t)
def searchMultiChain(self, startLayer, startConfig, globalBatch: int, totalGpus: int, verbose=True):
maximumOptionListSize = 0
k = len(startLayer.nextLayers)
llist = [[startLayer] for j in range(k)]
endLayer = None
for j in range(k):
l = startLayer.nextLayers[j]
while len(l.prevLayers) == 1: # Until join happens.
llist[j].append(l)
if len(l.nextLayers) > 1:
print("[searchMultiChain] ERROR! nested multi-chain. TODO; implement handling of this.")
l = l.nextLayers[0]
if endLayer == None:
endLayer = l
else:
assert(endLayer == l)
print("Found %d chains, branching at %d-th layer, joining at %d-th layer" % (k, startLayer.id, endLayer.id))
# Start dynamic programming.
time_start = time.time()
def generateAllConfigs(k: int, llist: list):
if k == 0:
return [[]]
configs = []
for laterPart in generateAllConfigs(k-1, llist[1:]):
configs.append([(0, startConfig)] + laterPart)
for nextIndex in range(1, len(llist[0])):
for config in self.listConfigOptions(llist[0][nextIndex], globalBatch, totalGpus):
laterPartList = generateAllConfigs(k-1, llist[1:])
# print("[generateAllConfigs] for k=%d, (%d, %s), got %s" % (k, nextIndex, str(config), str(laterPartList)))
for laterPart in laterPartList:
completePart = [(nextIndex, config)] + laterPart
configs.append(completePart)
return configs
# allCombinedIdx = generateAllConfigs(k, llist)
print("Total # of cell in table prefore config pruning: %d" % len(generateAllConfigs(k, llist)))
# TODO: replace this with carefully pruned config matrix.
configOptionLists = []
for j in range(k):
prevTotalStateCombo = 1
configOptionLists.append( [ [startConfig] ] )
print("[Pruning configs] %d-th chain, before prune: [" % j, end="")
for idx in range(1, len(llist[j])):
configOptionLists[j].append(self.listConfigOptions(llist[j][idx], globalBatch, totalGpus))
print(" %2d" % len(configOptionLists[j][idx]), end="")
prevTotalStateCombo *= len(configOptionLists[j][idx])
configOptionLists[j].append(self.listConfigOptions(endLayer, globalBatch, totalGpus))
print(" ] (%d combos)" % prevTotalStateCombo, end="")
for prunIter in range(3):
print(" ==> after prune (pass %d): [" % (prunIter + 1), end="")
totalStateCombo = 1
for idx in range(1, len(llist[j])):
prevLayer = llist[j][idx-1]
layer = llist[j][idx]
nextLayer = llist[j][idx + 1] if (idx + 1 < len(llist[j])) else endLayer
selectedConfigs = []
for nextConfig in configOptionLists[j][idx + 1]:
for prevConfig in configOptionLists[j][idx - 1]:
bestConfigByGpuCount = {}
for config in configOptionLists[j][idx]:
gpusUsed = self.calcGpusNeeded(layer, config, globalBatch)
activationTime1, activationSizeMatrix = self.calcInputXfer(prevLayer, layer, prevConfig, config)
activationTime2, activationSizeMatrix = self.calcInputXfer(layer, nextLayer, config, nextConfig)
gpuTime = self.benchGpuTime(layer, config)
totalTime = activationTime1 + activationTime2 + gpuTime
if gpusUsed not in bestConfigByGpuCount or \
totalTime < bestConfigByGpuCount[gpusUsed][0]:
bestConfigByGpuCount[gpusUsed] = (totalTime, config)
gpuCountList = bestConfigByGpuCount.keys()
previousSelectedTime = 999999999
for gpuCount in sorted(gpuCountList):
if bestConfigByGpuCount[gpuCount][0] < previousSelectedTime * 0.9: # Don't use more GPUs unless it reduce time by 10% or more.
previousSelectedTime = bestConfigByGpuCount[gpuCount][0]
if bestConfigByGpuCount[gpuCount][1] not in selectedConfigs:
selectedConfigs.append(bestConfigByGpuCount[gpuCount][1])
configOptionLists[j][idx] = selectedConfigs
print(" %2d" % len(configOptionLists[j][idx]), end="")
totalStateCombo *= len(configOptionLists[j][idx])
print(" ] (%d combos)" % totalStateCombo, end="")
# Stop prunning if it is converged.
if totalStateCombo == prevTotalStateCombo:
break
prevTotalStateCombo = totalStateCombo
print("")
configOptionLists[j].pop() # remove configs of endLayer
def generatePrunedCombo(branchIdx: int, configOptionLists: list):
if branchIdx == len(configOptionLists):
return [[]]
combos = []
for idx in range(len(configOptionLists[branchIdx])):
for config in configOptionLists[branchIdx][idx]:
laterPartList = generatePrunedCombo(branchIdx + 1, configOptionLists)
# print("[generateAllConfigs] for k=%d, (%d, %s), got %s" % (k, nextIndex, str(config), str(laterPartList)))
for laterPart in laterPartList:
completePart = [(idx, config)] + laterPart
combos.append(completePart)
return combos
allCombinedIdx = generatePrunedCombo(0, configOptionLists)
initialIdx = tuple(allCombinedIdx[0])
t = {}
# t[initialIdx] = [(numpy.zeros(k, dtype=numpy.int32), numpy.zeros(totalGpus, dtype=numpy.int32), (0, startConfig))]
t[initialIdx] = [([0 for j in range(k)], [0 for j in range(totalGpus)], (-1, startConfig, 0))]
# t[initialIdx] = [(array('i', [0 for j in range(k)]), [0 for j in range(totalGpus)], (0, startConfig))]
optionsConsideredTotal = 0
optionsAfterMinTotal = 0
# configOptionLists = [[] for j in range(k)]
# for j in range(k):
# configOptionLists[j].append([startConfig])
# for idx in range(1, len(llist[j])):
# configOptionLists[j].append(self.listConfigOptions(llist[j][idx], globalBatch, totalGpus))
if verbose:
print("Total # of cells in table: %d, configGeneration took: %d sec" % (len(allCombinedIdx), time.time() - time_start))
for combinedIdxAndConfig in allCombinedIdx[1:]:
# print(combinedIdx)
combined = tuple(combinedIdxAndConfig)
t[combined] = []
prefilteredOptions = []
for j in range(k):
prevIdx = combinedIdxAndConfig[j][0] - 1
if prevIdx < 0:
continue
currentIdx = combinedIdxAndConfig[j][0]
layer = llist[j][currentIdx]
prevLayer = llist[j][prevIdx]
currentConfig = combinedIdxAndConfig[j][1]
gpuTime = int(self.benchGpuTime(layer, currentConfig))
for prevConfig in configOptionLists[j][prevIdx]: #prevConfigList:
prevCombinedIdxAndConfig = combinedIdxAndConfig.copy()
prevCombinedIdxAndConfig[j] = (prevIdx, prevConfig)
prevCombined = tuple(prevCombinedIdxAndConfig)
for optionIdx in range(len(t[prevCombined])):
prevTimeVec, prevGpuReady, prevStep = t[prevCombined][optionIdx]
# for (prevTimeVec, prevGpuReady, prevStep) in t[prevCombined]:
# compute time.
activationTime, activationSizeMatrix = self.calcInputXfer(prevLayer, layer, prevConfig, currentConfig)
# First, compute the earliest time it can finish j-th chain.
prevBranchReady = prevTimeVec[j]
gpusNeeded = self.calcGpusNeeded(layer, currentConfig, globalBatch)
newGpuReadyTimeVec = sorted(prevGpuReady, reverse=True)
prevGpuReadyTime = newGpuReadyTimeVec[totalGpus - gpusNeeded]
newStartTime = max(prevBranchReady, prevGpuReadyTime)
# newReadyTime = int(newStartTime + activationTime + gpuTime)
newReadyTime = newStartTime + int(activationTime) + gpuTime
newTimeVec = prevTimeVec.copy()
newTimeVec[j] = newReadyTime
gpusAssigned = 0
for i in range(totalGpus):
if newGpuReadyTimeVec[i] <= newStartTime:
newGpuReadyTimeVec[i] = newReadyTime
gpusAssigned += 1
if gpusAssigned >= gpusNeeded:
break
# # Experiment... bump always.
# bumpToTime = min(newGpuReadyTimeVec)
# bumpedTimeVec = [ max(timeElem, bumpToTime) for timeElem in newTimeVec ]
# prefilteredOptions.append((bumpedTimeVec, newGpuReadyTimeVec, (j, prevConfig, optionIdx) ))
prefilteredOptions.append((newTimeVec, newGpuReadyTimeVec, (j, prevConfig, optionIdx) ))
optionsConsideredTotal += len(prefilteredOptions)
# Filter by lamportMin.
skipIdicesForEqual = []
filteredIndices = []
for optionIdx in range(len(prefilteredOptions)):
if optionIdx in skipIdicesForEqual:
continue
(newTimeVec, newGpuReadyTimeVec, step) = prefilteredOptions[optionIdx]
bumpToTime = min(newGpuReadyTimeVec)
bumpedTimeVec = [ max(timeElem, bumpToTime) for timeElem in newTimeVec ]
# check if there's any other result that's clearly better than this.
foundBetterOption = False
for compareAgainstIdx in range(len(prefilteredOptions)):
if (optionIdx == compareAgainstIdx) or (compareAgainstIdx in filteredIndices):
continue
(cmpTimeVec, cmpGpuReadyTimeVec, cmpStep) = prefilteredOptions[compareAgainstIdx]
better = True
equal = True
for i in range(k):
if bumpedTimeVec[i] < cmpTimeVec[i]:
better = False
if bumpedTimeVec[i] != cmpTimeVec[i]:
equal = False
if better and (not equal):
foundBetterOption = True
if equal:
skipIdicesForEqual.append(compareAgainstIdx)
if foundBetterOption:
filteredIndices.append(optionIdx)
else:
t[combined].append(prefilteredOptions[optionIdx])
# print("[MultiChain] t[%50s] (%3d->%3d options)= %s" %
# (str(combined), len(prefilteredOptions), len(t[combined]), str(t[combined])))
if len(t[combined]) == 0:
print(" ****** prefilteredOptions: %s" % str(prefilteredOptions))
maximumOptionListSize = max(maximumOptionListSize, len(t[combined]))
# optionListSizeList.append(len(t[combined]))
optionsAfterMinTotal += len(t[combined])
# TODO: Final join to end layer.
configToTimeDict = {}
def generatePrunedCombo(branchIdx: int, configOptionLists: list):
if branchIdx == len(configOptionLists):
return [[]]
combos = []
for idx in range(len(configOptionLists[branchIdx])):
for config in configOptionLists[branchIdx][idx]:
laterPartList = generatePrunedCombo(branchIdx + 1, configOptionLists)
# print("[generateAllConfigs] for k=%d, (%d, %s), got %s" % (k, nextIndex, str(config), str(laterPartList)))
for laterPart in laterPartList:
completePart = [(idx, config)] + laterPart
combos.append(completePart)
return combos
# def generateFinalConfigs(k: int, llist: list):
# if k == 0:
# return [[]]
# configs = []
# for config in self.listConfigOptions(llist[0][-1], globalBatch, totalGpus):
# laterPartList = generateFinalConfigs(k-1, llist[1:])
# for laterPart in laterPartList:
# completePart = [(len(llist[0])-1, config)] + laterPart
# configs.append(completePart)
# return configs
def generateFinalPrunedCombos(branchIdx: int, configOptionLists: list):
if branchIdx == len(configOptionLists):
return [[]]
combos = []
for config in configOptionLists[branchIdx][-1]:
laterPartList = generateFinalPrunedCombos(branchIdx + 1, configOptionLists)
for laterPart in laterPartList:
completePart = [(len(configOptionLists[branchIdx])-1, config)] + laterPart
combos.append(completePart)
return combos
# finalCombinedList = generateFinalConfigs(k, llist)
finalCombinedList = generateFinalPrunedCombos(0, configOptionLists)
for endConfig in self.listConfigOptions(endLayer, globalBatch, totalGpus):
gpuTime = self.benchGpuTime(endLayer, endConfig)
bestTime = 9999999999999
optionWithBestTime = None
for combinedIdxAndConfig in finalCombinedList:
# activation time.
activationTimeSum = 0
activationTimeList = []
for j in range(k):
prevConfig = combinedIdxAndConfig[j][1]
activationTime, temp = self.calcInputXfer(llist[j][-1], endLayer, prevConfig, endConfig)
activationTimeSum += activationTime
activationTimeList.append(activationTime)
# traverse all options..
for optionIdx in range(len(t[tuple(combinedIdxAndConfig)])):
timeVec, gpuReady, prevStep = t[tuple(combinedIdxAndConfig)][optionIdx]
# for timeVec, gpuReady, prevStep in t[tuple(combinedIdxAndConfig)]:
# First, compute the earliest time it can finish j-th chain.
endTime = max(timeVec) + activationTimeSum + gpuTime
if endTime < bestTime:
bestTime = endTime
optionWithBestTime = (tuple(combinedIdxAndConfig), optionIdx)
configToTimeDict[endConfig] = (bestTime, optionWithBestTime)
if verbose:
avgOptionListSize = optionsAfterMinTotal / len(allCombinedIdx)
elapsedTime = time.time() - time_start
print("[searchMultiChain] took: %d sec (%.3f ms per cell)" % (elapsedTime, 1000 * elapsedTime / len(allCombinedIdx)))
print("[searchMultiChain] maximumOptionListSize: %d, avg: %.2f, pre-lamportMin: %.2f" % (maximumOptionListSize, avgOptionListSize, optionsConsideredTotal / len(allCombinedIdx)))
return (endLayer, configToTimeDict, t)
def displayMultiChainResult(self, endLayer, endConfig: tuple, t, bestJoiningOption):
bestJoiningCombinedIdxAndConfig, optionIdx = bestJoiningOption
combined = bestJoiningCombinedIdxAndConfig
schedule = [] # list of (branch, idx, config, endTime)
while True:
newTimeVec, newGpuReadyTimeVec, (j, prevConfig, prevOptionIdx) = t[combined][optionIdx]
if j == -1: # reached to the branching point.
break
schedule.append( (j, combined[j][0], combined[j][1], newTimeVec[j]) )
nextCombined = list(combined)
nextCombined[j] = (combined[j][0] - 1, prevConfig)
combined = tuple(nextCombined)
optionIdx = prevOptionIdx
for i in range(len(schedule)-1, -1, -1):
(branch, idx, config, endTime) = schedule[i]
print("%sLayer(%d, %2d) config: %15s done at %d" % (" "*55*branch, branch, idx, config, endTime))
def searchBestSplits(self, totalGpus: int, globalBatch: int = 16, amplificationLimit: float = 2.0, dataParallelBaseline = False, spatialSplit=False):
t = [[] for i in range(len(self.layers))] # [layer] = list of (config, cumulativeTime, prevConfigIndex)
initialConfigs = []
initialTimes = []
bestConfigList = []
bestTimeList = []
bestDataParallelTimeList = []
for i in range(len(self.layers)):
layer = self.layers[i]