forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_parallel_model.py
2222 lines (1916 loc) · 81.2 KB
/
data_parallel_model.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
## @package data_parallel_model
# Module caffe2.python.data_parallel_model
from collections import OrderedDict
from future.utils import viewitems, viewkeys, viewvalues
import logging
import copy
from multiprocessing import cpu_count
from caffe2.python import \
model_helper, dyndep, scope, workspace, core, memonger, utils
from caffe2.proto import caffe2_pb2
import numpy as np
import warnings
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops")
# We only import nccl operators when the machine has GPUs
# Otherwise the binary can be compiled with CPU-only mode, and
# will not be able to find those modules
if workspace.NumGpuDevices() > 0:
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/nccl:nccl_ops")
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops_gpu")
log = logging.getLogger("data_parallel_model")
log.setLevel(logging.INFO)
_DEFAULT_TIMEOUT_SEC = 30
_DEFAULT_BARRIER_NET_TIMEOUT_SEC = 300
def Parallelize_GPU(*args, **kwargs):
kwargs['cpu_device'] = False
Parallelize(*args, **kwargs)
def Parallelize_CPU(*args, **kwargs):
kwargs['cpu_device'] = True
Parallelize(*args, **kwargs)
def Parallelize_iDeep(*args, **kwargs):
kwargs['ideep'] = True
Parallelize(*args, **kwargs)
def Parallelize(
model_helper_obj,
input_builder_fun,
forward_pass_builder_fun,
param_update_builder_fun=None,
optimizer_builder_fun=None,
post_sync_builder_fun=None,
pre_grad_net_transformer_fun=None,
net_transformer_fun=None,
devices=None,
rendezvous=None,
net_type='dag',
broadcast_computed_params=True,
optimize_gradient_memory=False,
dynamic_memory_management=False,
blobs_to_keep=None,
use_nccl=False,
max_concurrent_distributed_ops=16,
cpu_device=False,
ideep=False,
num_threads_per_device=4,
shared_model=False,
combine_spatial_bn=False,
barrier_net_timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC,
):
'''
Function to create a model that can run on many GPUs or CPUs.
model_helper_obj: an object of ModelHelper
input_builder_fun:
Function that adds the input operators
Note: Remember to instantiate reader outside of this
function so all devices share same reader object.
Signature: input_builder_fun(model)
forward_pass_builder_fun:
Function to add the operators to the model.
Must return list of loss-blob references that
are used to build the gradient. Loss scale parameter
is passed, as you should scale the loss of your model
by 1.0 / the total number of devices.
Signature: forward_pass_builder_fun(model, loss_scale)
param_update_builder_fun:
Function that adds operators that are run after
gradient update, such as updating the weights and
weight decaying. This is called for each GPU separately.
Signature: param_update_builder_fun(model)
optimizer_builder_fun:
Alternative to param_update_builder_fun, allows one
to add an optimizer for the whole model. Called only
once, without name or devicescope.
net_transformer_fun:
Optional function to transform the network after the
network is built. It will be called once (NOT once per
GPU.)
Signature:
net_transformer_fun(
model, num_devices, device_prefix, device_type)
pre_grad_net_transformer_fun:
Optional function to transform the network similar to
net_transformer_fun, but happens before gradient ops
been add.
Signature: pre_grad_net_transformer_fun(model)
post_sync_builder_fun:
Function applied after initial parameter sync has been
completed, such as keeping multi-precision parameters
in sync.
Signature: post_sync_builder_fun(model)
devices: List of GPU ids, such as [0, 1, 2, 3],
rendezvous: used for rendezvous in distributed computation, if None
then only one node is used. To create rendezvous,
use <TBD>.
net_type: Network type
optimize_gradient_memory: whether to apply 'memonger' to share blobs
shared_model (only for CPU) use same parameters on each device
in gradient computation to reduce memory footprint.
dynamic_memory_management: Whether to apply dynamic memory optimization
by freeing unused blobs. The underlying (de)allocation
uses cached allocator. For GPU training PLEASE MAKE SURE
caffe2_cuda_memory_pool is set.
blobs_to_keep : A list of blob names to keep and don't free during
dynamic memory optimization (for example loss blob).
cpu_device Use CPU instead of GPU.
ideep Use ideep.
combine_spatial_bn:
When set to True, applies batch normalization across
all devices within the node. If False, batch
normalization will be done separately for each device.
This option is currently only supported on the CPU.
barrier_net_timeout_sec:
The timeout in seconds of the barrier net, which is run
to synchronize shards before a training epoch starts.
Defaults to 300 seconds.
'''
assert scope.CurrentDeviceScope() is None \
or scope.CurrentDeviceScope().device_type == caffe2_pb2.CPU, \
"Parallelize must be called without device-scope, \
device scope was: {}".format(scope.CurrentDeviceScope())
if devices is None:
if not (cpu_device or ideep):
devices = list(range(0, workspace.NumCudaDevices()))
else:
devices = list(range(0, cpu_count()))
if not (cpu_device or ideep):
for gpu in devices:
if gpu >= workspace.NumGpuDevices():
log.warning("** Only {} GPUs available, GPUs {} requested".format(
workspace.NumGpuDevices(), devices))
break
model_helper_obj._device_type = workspace.GpuDeviceType
model_helper_obj._device_prefix = "gpu"
model_helper_obj._shared_model = False
device_name = "GPU"
assert shared_model is False, "Shared model only supported on CPU"
elif ideep:
model_helper_obj._device_type = caffe2_pb2.IDEEP
model_helper_obj._device_prefix = "ideep"
device_name = "IDEEP"
model_helper_obj._shared_model = shared_model
if shared_model and rendezvous is not None:
assert "Shared model only supported on single-node currently"
else:
model_helper_obj._device_type = caffe2_pb2.CPU
model_helper_obj._device_prefix = "cpu"
device_name = "CPU"
model_helper_obj._shared_model = shared_model
if shared_model and rendezvous is not None:
assert "Shared model only supported on single-node currently"
log.info("Parallelizing model for devices: {}".format(devices))
extra_workers = 8 if rendezvous is not None else 0 # best-guess
num_workers = len(devices) * num_threads_per_device + extra_workers
max_concurrent_distributed_ops =\
min(max_concurrent_distributed_ops, num_workers - 1)
model_helper_obj.net.Proto().num_workers = num_workers
model_helper_obj.net.Proto().type = net_type
# Store some information in the model -- a bit ugly
model_helper_obj._devices = devices
model_helper_obj._rendezvous = rendezvous
model_helper_obj._sync_barrier_net = None
model_helper_obj._broadcast_context = None
model_helper_obj._grad_names = []
assert isinstance(model_helper_obj, model_helper.ModelHelper)
# Keep track of params that were in the model before: they are not
# data parallel, so we need to handle them separately
non_datapar_params = copy.copy(model_helper_obj.params)
# Add input and model
log.info("Create input and model training operators")
losses_by_gpu = {}
num_shards = 1 if rendezvous is None else rendezvous['num_shards']
loss_scale = 1.0 / (len(devices) * num_shards)
has_parameter_updates = param_update_builder_fun is not None or \
optimizer_builder_fun is not None
assert not (
param_update_builder_fun is not None and
optimizer_builder_fun is not None
), 'Can only specify one of param_update_builder_fun, optimizer_builder_fun'
# Check that a model that is used for validation/testing has
# init_params False, otherwise running the param init net will overwrite
# synchronized values by the training net
if not has_parameter_updates and model_helper_obj.init_params:
log.warning('')
log.warning("############# WARNING #############")
log.warning("Model {}/{} is used for testing/validation but".format(
model_helper_obj.name, model_helper_obj))
log.warning("has init_params=True!")
log.warning("This can conflict with model training.")
log.warning("Please ensure model = ModelHelper(init_params=False)")
log.warning('####################################')
log.warning('')
# TODO: make into assert
for device in devices:
device_opt = core.DeviceOption(model_helper_obj._device_type, device)
with core.DeviceScope(device_opt):
with core.NameScope("{}_{}".format(model_helper_obj._device_prefix,
device)):
log.info("Model for {} : {}".format(device_name, device))
input_builder_fun(model_helper_obj)
losses = forward_pass_builder_fun(model_helper_obj, loss_scale)
# Losses are not needed for test net
if has_parameter_updates:
assert isinstance(losses, list), \
'Model builder function must return list of loss blobs'
for loss in losses:
assert isinstance(loss, core.BlobReference), \
'Model builder func must return list of loss blobs'
losses_by_gpu[device] = losses
_ValidateParams(model_helper_obj.params)
# Create parameter map
model_helper_obj._device_grouped_blobs =\
_GroupByDevice(model_helper_obj, devices,
model_helper_obj.params, non_datapar_params)
# computed params
computed_params_grouped =\
_GroupByDevice(model_helper_obj, devices,
model_helper_obj.GetComputedParams(''), [])
model_helper_obj._device_grouped_blobs.update(computed_params_grouped)
model_helper_obj._param_names =\
list(viewkeys(model_helper_obj._device_grouped_blobs))
model_helper_obj._computed_param_names =\
list(viewkeys(computed_params_grouped))
if pre_grad_net_transformer_fun:
pre_grad_net_transformer_fun(model_helper_obj)
if has_parameter_updates:
log.info("Adding gradient operators")
_AddGradientOperators(devices, model_helper_obj, losses_by_gpu)
if net_transformer_fun:
net_transformer_fun(
model_helper_obj,
len(devices),
model_helper_obj._device_prefix,
model_helper_obj._device_type)
if not has_parameter_updates:
log.info("Parameter update function not defined --> only forward")
_InferBlobDevice(model_helper_obj)
return
if combine_spatial_bn:
assert(has_parameter_updates), \
'combine_spatial_bn should only be used for train model'
_InterleaveOps(model_helper_obj)
if cpu_device:
_CPUInterDeviceBatchNormalization(model_helper_obj)
else:
_GPUInterDeviceBatchNormalization(model_helper_obj)
_ValidateParams(model_helper_obj.params)
# Group gradients by device and register to blob lookup
param_to_grad = model_helper_obj.param_to_grad
grads_ordered = [param_to_grad[p] for p in
model_helper_obj.params if p in param_to_grad]
non_datapar_grads = [param_to_grad[p] for p in non_datapar_params]
gradients_grouped = _GroupByDevice(
model_helper_obj,
devices,
grads_ordered,
non_datapar_grads
)
model_helper_obj._device_grouped_blobs.update(gradients_grouped)
model_helper_obj._grad_names = list(viewkeys(gradients_grouped))
model_helper_obj._losses_by_gpu = losses_by_gpu
_InferBlobDevice(model_helper_obj)
log.info("Add gradient all-reduces for SyncSGD")
if broadcast_computed_params:
_BroadcastComputedParams(devices, model_helper_obj, rendezvous, use_nccl)
if len(model_helper_obj._grad_names) > 0:
# Gradients in reverse order
reverse_ordered_grads = _GetReverseOrderedGrads(model_helper_obj)
assert(len(reverse_ordered_grads) > 0)
_AllReduceBlobs(
reverse_ordered_grads,
devices,
model_helper_obj,
model_helper_obj.net,
rendezvous,
use_nccl,
max_concurrent_distributed_ops,
)
else:
log.info("NOTE: Param builder function did not create any parameters.")
log.info("Post-iteration operators for updating params")
num_shards = 1 if rendezvous is None else rendezvous['num_shards']
all_params = set(model_helper_obj.GetParams(''))
if shared_model:
_PruneParametersForSharing(model_helper_obj)
if param_update_builder_fun is not None:
for device in devices:
device_opt = core.DeviceOption(model_helper_obj._device_type, device)
with core.DeviceScope(device_opt):
with core.NameScope(
"{}_{}".format(model_helper_obj._device_prefix, device)
):
param_update_builder_fun(model_helper_obj)
else:
log.info("Calling optimizer builder function")
optimizer = optimizer_builder_fun(model_helper_obj)
model_helper_obj._optimizer = optimizer
(sync_blobs, sync_names) = _ComputeBlobsToSync(model_helper_obj)
sync_blobs_grouped = _GroupByDevice(
model_helper_obj,
devices,
sync_blobs,
[],
)
model_helper_obj._device_grouped_blobs.update(sync_blobs_grouped)
_InferBlobDevice(model_helper_obj)
_AnalyzeOperators(model_helper_obj)
# Configure dagnet to run with only one worker on the first iteration,
# to prevent concurrency problems with allocs and nccl.
arg = model_helper_obj.Proto().arg.add()
arg.name = "first_iter_only_one_worker"
arg.i = 1
# Add initial parameter syncs
log.info("Add initial parameter sync")
_SyncAllParams(
devices,
model_helper_obj,
model_helper_obj.param_init_net,
model_helper_obj.param_init_net,
rendezvous,
sync_names,
max_concurrent_distributed_ops=1
)
# Handle any operations that need to be done after parameter sync
# i.e. making sure multi-precision copies of parameters are up-to-date
if post_sync_builder_fun is not None:
for device in devices:
device_opt = core.DeviceOption(model_helper_obj._device_type, device)
with core.DeviceScope(device_opt):
with core.NameScope(
"{}_{}".format(model_helper_obj._device_prefix, device)
):
post_sync_builder_fun(model_helper_obj)
assert not (optimize_gradient_memory and dynamic_memory_management), \
"""It is not advised to use gradient optimization ('memonger')
with dynamic memory management."""
if optimize_gradient_memory:
_OptimizeGradientMemorySimple(model_helper_obj, losses_by_gpu, devices)
if dynamic_memory_management:
_AddDynamicMemoryOptimization(model_helper_obj, blobs_to_keep, devices)
model_helper_obj._data_parallel_model_init_nets = [
model_helper_obj.param_init_net,
]
model_helper_obj._data_parallel_model_nets = [
model_helper_obj.net
]
_AddBarrierToModelNets(model_helper_obj, barrier_net_timeout_sec)
if shared_model:
_RemapParameterBlobsForSharedModel(model_helper_obj, all_params)
def Parallelize_GPU_BMUF(*args, **kwargs):
kwargs['cpu_device'] = False
Parallelize_BMUF(*args, **kwargs)
def Parallelize_CPU_BMUF(*args, **kwargs):
kwargs['cpu_device'] = True
Parallelize_BMUF(*args, **kwargs)
def Parallelize_BMUF(
model_helper_obj,
input_builder_fun,
forward_pass_builder_fun,
param_update_builder_fun,
block_learning_rate=1.0,
block_momentum=None,
devices=None,
rendezvous=None,
net_type='dag',
master_device=None,
use_nccl=False,
nesterov=False,
optimize_gradient_memory=False,
reset_momentum_sgd=False,
warmup_iterations=None,
max_concurrent_distributed_ops=4,
add_blobs_to_sync=None,
num_threads_per_device=4,
cpu_device=False,
barrier_net_timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC,
):
'''
Function to create model that run on many GPUs and creates a net for
parameter_updates that can be run independently for number of iterations
then followed by another net that runs once to compute the final parameter
updates according to block wise model update filtering rule described
in : Scalable Training of Deep Learning Machines by Incremental Block
Training with Intra-block Parallel Optimization and Blockwise Model-Update
Filtering (ICASSP 2016).
'''
assert scope.CurrentDeviceScope() is None \
or scope.CurrentDeviceScope().device_type == caffe2_pb2.CPU, \
"Parallelize must be called without device-scope, \
device scope was: {}".format(scope.CurrentDeviceScope())
assert isinstance(model_helper_obj, model_helper.ModelHelper)
if devices is None:
devices = list(range(0, workspace.NumGpuDevices()))
if master_device is None:
master_device = devices[0]
if not cpu_device:
for gpu in devices:
if gpu >= workspace.NumGpuDevices():
log.warning("** Only {} GPUs available, GPUs {} requested".format(
workspace.NumGpuDevices(), devices))
break
model_helper_obj._device_type = workspace.GpuDeviceType
model_helper_obj._device_prefix = "gpu"
else:
model_helper_obj._device_type = caffe2_pb2.CPU
model_helper_obj._device_prefix = "cpu"
model_helper_obj._devices = devices
model_helper_obj._rendezvous = rendezvous
model_helper_obj._sync_barrier_net = None
model_helper_obj._broadcast_context = None
model_helper_obj._shared_model = False
master_dev_opt = core.DeviceOption(model_helper_obj._device_type, master_device)
# question: rendezvous structure
num_shards = rendezvous['num_shards'] if rendezvous else 1
# num_devices is #devices across all machines
num_devices = len(devices) * num_shards
# num_workers is #threads to execute the DAG per shard
num_workers = num_threads_per_device * len(devices)
if rendezvous:
num_workers += 8
loss_scale = 1.0 / num_devices
if block_momentum is None:
block_momentum = 1.0 - 1.0 / num_devices
max_concurrent_distributed_ops = min(
max_concurrent_distributed_ops,
num_workers - 1
)
model_helper_obj.net.Proto().num_workers = num_workers
model_helper_obj.net.Proto().type = net_type
# A net for initializing global model parameters. Its called once in the
# same step as net parameters initialization.
model_helper_obj._global_model_init_net = core.Net('global_model_init')
model_helper_obj._global_model_init_net.Proto().type = net_type
model_helper_obj._global_model_init_net.Proto().num_workers = \
num_workers
# A net for computing final parameter updates. Its will run once after
# running net (local models updates) for `num_local_iterations` times.
model_helper_obj._global_model_param_updates_net = core.Net('global_model')
model_helper_obj._global_model_param_updates_net.Proto().type = net_type
model_helper_obj._global_model_param_updates_net.Proto().num_workers = \
num_workers
def _v(param):
return "{}_v".format(param)
def _g(param):
return "{}_g".format(param)
def _v_prev(param):
return "{}_prev".format(param)
# Keep track of params that were in the model before: they are not
# data parallel, so we need to handle them separately
non_datapar_params = copy.copy(model_helper_obj.params)
model_helper_obj._losses_by_gpu = {}
def _InitializeModels(gpu_id):
input_builder_fun(model_helper_obj)
loss = forward_pass_builder_fun(model_helper_obj, loss_scale)
model_helper_obj._losses_by_gpu[gpu_id] = loss
_ForEachDevice(
devices,
_InitializeModels,
device_type=model_helper_obj._device_type,
device_prefix=model_helper_obj._device_prefix,
scoped=True
)
_ValidateParams(model_helper_obj.params)
model_helper_obj._device_grouped_blobs =\
_GroupByDevice(model_helper_obj, devices,
model_helper_obj.params, non_datapar_params)
model_helper_obj._param_names =\
list(viewkeys(model_helper_obj._device_grouped_blobs))
_AddGradientOperators(
devices, model_helper_obj, model_helper_obj._losses_by_gpu
)
_ValidateParams(model_helper_obj.params)
_InferBlobDevice(model_helper_obj)
def _InitializeParamUpdate(gpu_id):
param_update_builder_fun(model_helper_obj)
_ForEachDevice(
devices,
_InitializeParamUpdate,
device_type=model_helper_obj._device_type,
device_prefix=model_helper_obj._device_prefix,
scoped=True
)
model_parameter_names = list(
viewkeys(model_helper_obj._device_grouped_blobs)
)
if warmup_iterations is not None:
model_helper_obj._warmup_iterations = warmup_iterations
# A net for broadcasting gpu-0 (master shard) parameters after
# running net for `warmup_iterartions`.
model_helper_obj._warmup_broadcast = core.Net('warmup-broadcast')
model_helper_obj._warmup_broadcast.Proto().type = net_type
model_helper_obj._warmup_broadcast.Proto().num_workers = \
num_workers
_SyncAllParams(
devices,
model_helper_obj,
model_helper_obj.param_init_net,
model_helper_obj._warmup_broadcast,
rendezvous,
model_parameter_names,
max_concurrent_distributed_ops
)
for param_name in viewkeys(model_helper_obj._device_grouped_blobs):
param = model_helper_obj._device_grouped_blobs[param_name][master_device]
with core.DeviceScope(master_dev_opt):
model_helper_obj._warmup_broadcast.Copy(param, _g(param))
# (Step-0) Initialize momentum parameters on master device.
for param_name in viewkeys(model_helper_obj._device_grouped_blobs):
param = model_helper_obj._device_grouped_blobs[param_name][master_device]
with core.DeviceScope(master_dev_opt):
model_helper_obj._global_model_init_net.ConstantFill(
param, _v(param), value=0.0
)
model_helper_obj._global_model_init_net.Copy(param, _g(param))
if nesterov:
model_helper_obj._global_model_init_net.ConstantFill(
param, _v_prev(param), value=0.0
)
# (Step-1) Update models for num_local_iterations.
# (Step-2) Compute post-local-updates average of the params.
# Sum model params across GPUs and store resutls in param_avg blob.
_AllReduceBlobs(
model_parameter_names,
devices,
model_helper_obj,
model_helper_obj._global_model_param_updates_net,
rendezvous,
use_nccl,
max_concurrent_distributed_ops
)
# (Step-3) Update momentum params :
# param_v = block_momentum * param_v
# + block_learning_Rate * (param_avg - param)
# if nesterov momentum:
# param = param + param_v
# - block_momentum * (param_v - param_v_prev)
# param_v_prev = param_v
# else:
# param = param + param_v
for param_name in model_parameter_names:
param = model_helper_obj._device_grouped_blobs[param_name][master_device]
with core.DeviceScope(master_dev_opt):
# TODO(ataei) : Stop building the graph here to get model average ?
model_helper_obj._global_model_param_updates_net.Scale(
param, param, scale=1.0 / num_devices
)
model_helper_obj._global_model_param_updates_net.Sub(
[param, _g(param)], param
)
model_helper_obj._global_model_param_updates_net.Scale(
param, param, scale=block_learning_rate
)
model_helper_obj._global_model_param_updates_net.Scale(
_v(param), _v(param), scale=block_momentum
)
model_helper_obj._global_model_param_updates_net.Add(
[_v(param), param], _v(param)
)
model_helper_obj._global_model_param_updates_net.Add(
[_g(param), _v(param)], _g(param)
)
if nesterov:
model_helper_obj._global_model_param_updates_net.Sub(
[_v(param), _v_prev(param)], _v_prev(param)
)
model_helper_obj._global_model_param_updates_net.Scale(
_v_prev(param), _v_prev(param), scale=block_momentum
)
model_helper_obj._global_model_param_updates_net.Sub(
[_g(param), _v_prev(param)], _g(param)
)
model_helper_obj._global_model_param_updates_net.Copy(
_v(param), _v_prev(param)
)
model_helper_obj._global_model_param_updates_net.Copy(
_g(param), param
)
_SyncAllParams(
devices,
model_helper_obj,
model_helper_obj.param_init_net,
model_helper_obj._global_model_param_updates_net,
rendezvous,
model_parameter_names,
max_concurrent_distributed_ops
)
# Add additional syncs
if add_blobs_to_sync is not None:
AddBlobSync(
model_helper_obj,
add_blobs_to_sync,
net=model_helper_obj._global_model_param_updates_net)
# Reset momentum-SGD parameters
if reset_momentum_sgd:
momentum_ops = [op for op in model_helper_obj.net.Proto().op
if op.type == 'MomentumSGDUpdate']
for op in momentum_ops:
momentum_blob = op.input[1]
with core.DeviceScope(op.device_option):
model_helper_obj._global_model_param_updates_net.ConstantFill(
[momentum_blob], momentum_blob, value=0.0
)
if optimize_gradient_memory:
_OptimizeGradientMemorySimple(
model_helper_obj, model_helper_obj._losses_by_gpu, devices
)
model_helper_obj._data_parallel_model_init_nets = [
model_helper_obj.param_init_net,
model_helper_obj._global_model_init_net
]
model_helper_obj._data_parallel_model_nets = [
model_helper_obj.net,
(model_helper_obj._global_model_param_updates_net, 1)
]
_AddBarrierToModelNets(model_helper_obj, barrier_net_timeout_sec)
def CreateNet(model, overwrite=False):
for net_iters in model._data_parallel_model_nets:
if isinstance(net_iters, tuple):
workspace.CreateNet(net_iters[0], overwrite=overwrite)
else:
workspace.CreateNet(net_iters, overwrite=overwrite)
def RunInitNet(model):
for init_net in model._data_parallel_model_init_nets:
workspace.RunNetOnce(init_net)
CreateNet(model)
def RunWarmup(model):
workspace.RunNet(model.net, model._warmup_iterations)
workspace.RunNetOnce(model._warmup_broadcast)
def RunNet(model, num_iterations):
for net_iter in model._data_parallel_model_nets:
if isinstance(net_iter, tuple):
workspace.RunNet(net_iter[0].Proto().name, net_iter[1])
else:
workspace.RunNet(net_iter, num_iterations)
def _AddBarrierToModelNets(model, barrier_net_timeout_sec):
if model._rendezvous is not None and model._rendezvous['engine'] == 'GLOO':
# Synchronize DPM at the start of each epoch. This allows shards that
# starts an epoch sooner to wait for slower shards. Without this,
# shards that are faster than others will begin training the next epoch
# while stragglers are blocked on IO, and may timeout after 30 seconds
# (_DEFAULT_TIMEOUT_SEC).
# We pass in model.param_init_net so that the barrier net can be run as
# part of the param_init_net.
model._barrier_init_net = core.Net("barrier_init_net")
model._barrier_net = _CreateBarrierNet(model, model._barrier_init_net,
"pre_training", barrier_net_timeout_sec)
model._data_parallel_model_init_nets.insert(0, model._barrier_init_net)
model._data_parallel_model_nets.insert(0, model._barrier_net)
def _CreateBarrierNet(model, init_net, name_prefix, timeout_sec):
log.info("Creating barrier net")
assert model._rendezvous['engine'] == 'GLOO', "Engine does not support barrier"
comm_world = _CreateOrCloneCommonWorld(
init_net,
name_prefix + "_barrier_cw",
rendezvous=model._rendezvous,
timeout_sec=timeout_sec,
)
barrier_net = core.Net(name_prefix + "_barrier_net")
barrier_net.Barrier(
inputs=[comm_world],
outputs=[],
engine=model._rendezvous['engine'],
)
return barrier_net
# DEPRECATED: See warnings below.
def Synchronize(model, timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC):
warnings.warn("The Synchronize API has been deprecated. We now have a "
"barrier net which runs before training to ensure all hosts wait "
"before training starts. The default timeout for the barrier is "
"300s and it can be overridden using the barrier_net_timeout_sec "
"parameter when calling Parallelize.",
category=DeprecationWarning, stacklevel=2)
if model._rendezvous is None or model._rendezvous['num_shards'] <= 1:
# Single host case
return
if model._sync_barrier_net is None:
barrier_init_net = core.Net("sync_barrier_init_net")
model._sync_barrier_net = _CreateBarrierNet(
model, barrier_init_net, "sync", timeout_sec)
workspace.RunNetOnce(barrier_init_net)
workspace.CreateNet(model._sync_barrier_net)
model._sync_barrier_net_timeout = timeout_sec
assert model._sync_barrier_net_timeout == timeout_sec, \
"Must use fixed timeout, {} != {}".format(
model._sync_barrier_net_timeout, timeout_sec
)
log.info("Synchronize run barrier net.")
workspace.RunNet(model._sync_barrier_net)
def ConvertNetForDevice(net, device=None):
'''
Converts all blobs in the net to have namescope gpu_X, and correct
device scope. You can use this to enable AppendNet with a
forward_pass_builder_fun:
def builder_fun(model):
...
model.net.AppendNet(
data_parallel_model.ConvertNetForDevice(othermodel.net))
model.param_init_net.AppendNet(
data_parallel_model.ConvertNetForDevice(othermodel.param_init_net))
'''
mnet = copy.deepcopy(net)
if device is None:
device = scope.CurrentDeviceScope()
if core.IsGPUDeviceType(device.device_type):
device_prefix = "gpu"
elif device.device_type == caffe2_pb2.IDEEP:
device_prefix = "ideep"
else:
device_prefix = "cpu"
namescope = "{}_{}/".format(device_prefix, device.device_id)
for op in mnet.Proto().op:
if "RecurrentNetwork" in op.type:
raise NotImplementedError("RecurrentNetwork conversion not yet supported")
for i, inputb in enumerate(op.input):
op.input[i] = namescope + inputb
for i, outputb in enumerate(op.output):
op.output[i] = namescope + outputb
for i, blob in enumerate(op.control_input):
op.control_input[i] = namescope + blob
op.device_option.CopyFrom(device)
for i, einp in enumerate(mnet.Proto().external_input):
mnet.Proto().external_input[i] = namescope + einp
for i, eoutp in enumerate(mnet.Proto().external_output):
mnet.Proto().external_output[i] = namescope + eoutp
return mnet
def _ForEachDevice(devices, f, device_type, device_prefix, scoped=False,
*args, **kwargs):
for device in devices:
device_opt = core.DeviceOption(device_type, device)
with core.DeviceScope(device_opt):
if scoped:
with core.NameScope("{}_{}".format(device_prefix, device)):
f(device, *args, **kwargs)
else:
f(device, *args, **kwargs)
def _AddGradientOperators(devices, model, losses_by_gpu):
def create_grad(lossp):
return model.ConstantFill(lossp, str(lossp) + "_grad", value=1.0)
loss_grad = {}
# Explicitly need to create gradients on each GPU
for gpu_id in devices:
device = core.DeviceOption(model._device_type, gpu_id)
with core.DeviceScope(device):
for l in losses_by_gpu[gpu_id]:
lg = create_grad(l)
loss_grad[str(l)] = str(lg)
model.AddGradientOperators(loss_grad)
def ExtractPredictorNet(model, inputs, outputs, device):
'''
Returns (net, params) that can be exported to be used as a prediction
net.
'''
master_device = model._devices[0]
prefix = "{}_{}/".format(model._device_prefix, master_device)
prefix_inputs = [prefix + str(b) for b in inputs]
prefix_outputs = [prefix + str(b) for b in outputs]
(predictor_net, export_blobs) = model_helper.ExtractPredictorNet(
net_proto=model.net.Proto(),
input_blobs=prefix_inputs,
output_blobs=prefix_outputs,
device=device,
renames={
a: b
for (a, b) in zip(prefix_inputs + prefix_outputs, inputs + outputs)
},
)
return (predictor_net, export_blobs)
def GetCheckpointParams(model):
'''
Returns a set of blobs that are needed for a complete check point.
They are blobs for the first gpu and iteration blobs.
'''
(all_blobs, _) = _ComputeBlobsToSync(model)
first_gpu_blobs = {
b
for b in all_blobs
if str(b)
.startswith("{}_{}/".format(model._device_prefix, model._devices[0]))
}
# Add iteration blobs that do not have namescope separately, since
# it is important to checkpoint iteration counter
iteration_blobs = set()
for op in model.net.Proto().op:
if op.type == 'Iter' or op.type == 'AtomicIter':
if not op.output[0].startswith("{}_".format(model._device_prefix)):
iteration_blobs.add(op.output[0])
return first_gpu_blobs.union(iteration_blobs)
def FinalizeAfterCheckpoint(model, blobs=None, cpu_mode=False):
'''
This function should be called after loading parameters from a
checkpoint / initial parameters file.
'''
if not hasattr(model, "_checkpoint_net"):
if blobs is None:
(_, uniq_blob_names) = _ComputeBlobsToSync(model)
else:
uniq_blob_names = [stripBlobName(p) for p in blobs]
# Synchronize to the blob lookup map, as the provided
# blobs might have non-parameters, such as momentum blobs.
log.info("Creating checkpoint synchronization net")
devices = model.GetDevices()
for name in uniq_blob_names:
if name not in model._device_grouped_blobs:
grouped = {
d:
core.BlobReference("{}_{}{}{}".format(
model._device_prefix,
d,
scope._NAMESCOPE_SEPARATOR,
name)
) for d in devices}
model._device_grouped_blobs[name] = grouped
model._checkpoint_net = core.Net("checkpoint_sync_net")
if not cpu_mode:
model._checkpoint_net.RunAllOnGPU()
checkpoint_init_net = None
if (model._rendezvous is not None and model._rendezvous['num_shards'] > 1):
checkpoint_init_net = core.Net("checkpoint_init_net")
if not cpu_mode:
checkpoint_init_net.RunAllOnGPU()
_SyncAllParams(
devices,
model,
checkpoint_init_net,
model._checkpoint_net,
model._rendezvous,
uniq_blob_names,
max_concurrent_distributed_ops=1
)
if (checkpoint_init_net):
workspace.RunNetOnce(checkpoint_init_net)
workspace.CreateNet(model._checkpoint_net)
# Run the sync
log.info("Run checkpoint net")
workspace.RunNet(model._checkpoint_net.Proto().name)
def GetLearningRateBlobNames(model):
'''
Returns a list of learning rates blob names used in the optimizer.
'''
if model._optimizer is not None:
if model._device_type == caffe2_pb2.CPU or model._device_type == caffe2_pb2.IDEEP:
return [model._optimizer.get_cpu_blob_name('lr')]
elif core.IsGPUDeviceType(model._device_type):
return [model._optimizer.get_gpu_blob_name('lr', gpu, '')
for gpu in model._devices]
else:
raise Exception(
"Unsupported device type : {}".format(model._device_type)