forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimizer.py
2368 lines (2076 loc) · 81.4 KB
/
optimizer.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 optimizer
# Module caffe2.python.optimizer
import copy
import logging
from collections import defaultdict, namedtuple
from typing import Any, Dict
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import core, scope, utils, workspace
from caffe2.python.modeling import parameter_info
from past.builtins import basestring
_LEARNING_RATE_INJECTION = "lr_injection"
AuxOptimizerParams = namedtuple("AuxOptimizerParams", ["local", "shared"])
_optimizer_instance_count = defaultdict(int)
FP16_ENGINES = ["SIMD_Q_FP16", "SIMD_Q_STOC_FP16", "SIMD_Q_STOC_MKL_FP16"]
logger = logging.getLogger(__name__)
def reset_optimizer_instance_count():
"""
This function clears the _optimizer_instance_count. And keeps it
empty. This functionality is needed in some situations where
optimizer instance count might not reset even though the workplace is reset.
"""
_optimizer_instance_count.clear()
class Optimizer:
def __init__(self):
self._aux_params = AuxOptimizerParams(local=[], shared=[])
self._instance_num = _optimizer_instance_count[self.__class__.__name__]
_optimizer_instance_count[self.__class__.__name__] += 1
self._lr_multiplier = None
self._local_lr_multiplier = None
self._local_lr_multiplier_on_gpu = False
self._use_dedicated_lr_iteration_counter = False
"""
Adds optimization operators to the net for given parameter and its gradient
Parameter is specified by either 'param' being a ParameterInfo object.
In this case param.grad has to be set
Or by 'param' being a BlobReference and 'grad' being a BlobReference for its
gradient.
"""
def __call__(self, net, param_init_net, param, grad=None):
if grad is None:
assert isinstance(
param, parameter_info.ParameterInfo
), "Expected parameter to be of type ParameterInfo, got {}".format(param)
assert param.grad is not None
else:
if isinstance(param, basestring):
param = core.BlobReference(param)
param = parameter_info.ParameterInfo(param_id=None, param=param, grad=grad)
self._run(net, param_init_net, param)
def _run(self, net, param_init_net, param_info):
raise Exception("Not Implemented")
def get_cpu_blob_name(self, base_str, node_name=""):
classname = self.__class__.__name__
return "%s_%d_%s%s_cpu" % (classname, self._instance_num, base_str, node_name)
def get_gpu_blob_name(self, base_str, gpu_id, node_name):
classname = self.__class__.__name__
return "%s_%d_%s%s_gpu%d" % (
classname,
self._instance_num,
base_str,
node_name,
gpu_id,
)
@property
def attributes(self):
# return a dict that contains attributes related to init args only
attr = copy.deepcopy(self.__dict__)
del attr["_instance_num"]
return attr
@property
def use_dedicated_lr_iteration_counter(self):
return self._use_dedicated_lr_iteration_counter
@use_dedicated_lr_iteration_counter.setter
def use_dedicated_lr_iteration_counter(self, val):
self._use_dedicated_lr_iteration_counter = val
def make_unique_blob_name(self, base_str):
"""
Returns a blob name that will be unique to the current device
and optimizer instance.
"""
current_scope = scope.CurrentDeviceScope()
if current_scope is None:
return self.get_cpu_blob_name(base_str)
if core.IsGPUDeviceType(current_scope.device_type):
return self.get_gpu_blob_name(
base_str, current_scope.device_id, current_scope.node_name
)
else:
return self.get_cpu_blob_name(base_str, current_scope.node_name)
def build_lr(
self,
net,
param_init_net,
base_learning_rate,
learning_rate_blob=None,
policy="fixed",
iter_val=0,
**kwargs
):
if learning_rate_blob is None:
learning_rate_blob = self.make_unique_blob_name("lr")
if self._use_dedicated_lr_iteration_counter:
iteration = utils.BuildUniqueMutexIter(
param_init_net,
net,
iter=utils.OPTIMIZER_ITERATION_LR_NAME,
iter_mutex=utils.ITERATION_MUTEX_LR_NAME,
iter_val=iter_val,
)
logger.info(f"Created dedicated learning rate iteration counter: {iteration}")
else:
iteration = utils.BuildUniqueMutexIter(param_init_net, net, iter_val=iter_val)
if not net.BlobIsDefined(learning_rate_blob):
# There is one interesting thing here: since we are minimizing, we are
# doing "descent" so the learning rate is set to be negative.
lr = net.LearningRate(
[iteration],
learning_rate_blob,
base_lr=-base_learning_rate,
policy=policy,
**kwargs
)
else:
lr = net.GetBlobRef(learning_rate_blob)
if self._lr_multiplier is not None:
lr_multiplier = net.CopyFromCPUInput(
self._lr_multiplier, self.make_unique_blob_name("lr_multiplier")
)
lr = net.Mul(
[lr, lr_multiplier],
self.make_unique_blob_name("scaled_lr"),
broadcast=1,
)
if self._local_lr_multiplier is not None:
current_scope = scope.CurrentDeviceScope()
if (
current_scope is not None
and core.IsGPUDeviceType(current_scope.device_type)
and not self._local_lr_multiplier_on_gpu
):
local_lr_multiplier = net.CopyFromCPUInput(
self._local_lr_multiplier,
self.make_unique_blob_name("local_lr_multiplier"),
)
else:
local_lr_multiplier = self._local_lr_multiplier
lr = net.Mul(
[lr, local_lr_multiplier],
self.make_unique_blob_name("local_scaled_lr"),
broadcast=1,
)
return lr, iteration
def build_non_lr_iter(
self,
net,
param_init_net,
iter_val=0,
):
assert (
self._use_dedicated_lr_iteration_counter
), "This method should be only called when dedicated learning rate iteration counter is used."
iteration = utils.BuildUniqueMutexIter(param_init_net, net, iter_val=iter_val)
logger.info(f"Created iteration counter for non learning rate purposes: {iteration}")
# We need to create a dummy learning rate operator to enforce that
# iteration counter blob being placed in the trainer nodes. Otherwise,
# the Automatic Device Placement (ADP) algorithm for Hierachical
# Training (HT) will encounter issues to distribute blobs across group
# parameter servers. Note that this learning rate operator will not be
# used for any other purpose.
learning_rate_blob = self.make_unique_blob_name("iter_placement_hint")
if not net.BlobIsDefined(learning_rate_blob):
net.LearningRate(
[iteration],
learning_rate_blob,
base_lr=1.0,
policy="fixed",
)
return iteration
def add_lr_multiplier(self, lr_multiplier):
"""
Set the global learning rate multiplier. If a multiplier already
existed, this will overwrite the existing multiplier. The multiplier is
used for all future calls to _run(), unless it is overwritten.
"""
self._lr_multiplier = lr_multiplier
def _add_local_lr_multiplier(self, local_lr_multiplier, is_gpu_blob=False):
"""
Set the local learning rate multiplier. This local multiplier is
multiplied with the global learning rate multiplier if it exists. As
with the global learning rate multiplier, this multiplier will be
used for all future calls to _run(), so please call
_clear_local_lr_multiplier() at the beginning of the optimizer's _run()
before optionally calling this function.
"""
self._local_lr_multiplier = local_lr_multiplier
self._local_lr_multiplier_on_gpu = is_gpu_blob
def _clear_local_lr_multiplier(self):
self._local_lr_multiplier = None
self._local_lr_multiplier_on_gpu = False
@staticmethod
def dedup(net, sparse_dedup_aggregator, grad):
assert isinstance(
grad, core.GradientSlice
), "Dedup only works for sparse gradient, got {}".format(grad)
if sparse_dedup_aggregator:
return net.DeduplicateGradientSlices(
grad, aggregator=sparse_dedup_aggregator
)
else:
return grad
def get_auxiliary_parameters(self):
"""Returns a list of auxiliary parameters.
Returns:
aux_params: A namedtuple, AuxParams.
aux_params.local stores a list of blobs. Each blob is a local
auxiliary parameter. A local auxiliary parameter is a parameter in
parallel to a learning rate parameter. Take adagrad as an example,
the local auxiliary parameter is the squared sum parameter, because
every learning rate has a squared sum associated with it.
aux_params.shared also stores a list of blobs. Each blob is a shared
auxiliary parameter. A shared auxiliary parameter is a parameter
that is shared across all the learning rate parameters. Take adam as
an example, the iteration parameter is a shared parameter, because
all the learning rates share the same iteration parameter.
"""
return self._aux_params
# TODO(xlwang): In transfer learning, parameter initialized from pretrained
# model might require a different learning rate than otherwise initialized.
# To this end, here we implement a python solution where
# `base_learning_rate` is scaled by `scale`, by calling
# `scale_learning_rate`; Alternatively, we can achieve same effect by
# rewriting the LearningRate operator in C++
# Note that it is the responsibility of specific optimizer to decide what
# logic should be used for `scale_learning_rate`
def scale_learning_rate(self, *args, **kwargs):
raise NotImplementedError(
"Optimizer Need to Implement `scale_learning_rate` method."
)
def create_lars_inputs(self, param_init_net, weight_decay, trust, lr_max):
wd = param_init_net.ConstantFill(
[], "weight_decay", shape=[1], value=weight_decay
)
trust = param_init_net.ConstantFill([], "trust", shape=[1], value=trust)
lr_max = param_init_net.ConstantFill([], "lr_max", shape=[1], value=lr_max)
return wd, trust, lr_max
class SgdOptimizer(Optimizer):
def __init__(
self,
base_learning_rate=0.01,
policy="fixed",
momentum=0.0,
nesterov=True,
sparse_dedup_aggregator=None,
lars=None,
**kwargs
):
super().__init__()
self.base_learning_rate = base_learning_rate
self.policy = policy
self.momentum = momentum
self.nesterov = nesterov
self.sparse_dedup_aggregator = sparse_dedup_aggregator
self.lars = lars
self.init_kwargs = kwargs
def _run(self, net, param_init_net, param_info):
param = param_info.blob
grad = param_info.grad
if self.base_learning_rate == 0:
return
assert (
self.base_learning_rate > 0
), "Expect positive base learning rate, got {}".format(self.base_learning_rate)
self._clear_local_lr_multiplier()
# TODO(zqq): support LARS for sparse parameters
if self.lars is not None and not isinstance(grad, core.GradientSlice):
assert self.lars >= 0, "Lars offset must be nonnegative, got {}".format(
self.lars
)
wd, trust, lr_max = self.create_lars_inputs(
param_init_net, 0.0, 1.0, np.finfo(np.float32).max
)
lr_lars_multiplier = net.Lars(
[param, grad, wd, trust, lr_max],
self.make_unique_blob_name(str(param) + "_lars"),
offset=self.lars,
lr_min=0.0,
)
current_scope = scope.CurrentDeviceScope()
self._add_local_lr_multiplier(
lr_lars_multiplier,
is_gpu_blob=(
current_scope is not None
and core.IsGPUDeviceType(current_scope.device_type)
),
)
# We need negative sign for LR when used directly with WeightedSum
# below.
lr_sign = -1 if self.momentum else 1
lr, _ = self.build_lr(
net,
param_init_net,
base_learning_rate=self.base_learning_rate * lr_sign,
policy=self.policy,
**(self.init_kwargs)
)
dev = scope.CurrentDeviceScope()
if dev is None:
dev = core.DeviceOption(caffe2_pb2.CPU)
# Each GPU/CPU must have its own ONE blob, thus modify the name
# to include device information.
ONE = param_init_net.ConstantFill(
[],
"ONE_{}_{}{}".format(dev.device_type, dev.device_id, dev.node_name),
shape=[1],
value=1.0,
)
self._aux_params.shared.append(ONE)
if self.momentum > 0:
momentum_data = param_init_net.ConstantFill(
param, str(param) + "_momentum", value=0.0
)
self._aux_params.local.append(momentum_data)
if isinstance(grad, core.GradientSlice):
grad = self.dedup(net, self.sparse_dedup_aggregator, grad)
if self.momentum > 0.0:
net.SparseMomentumSGDUpdate(
[grad.values, momentum_data, lr, param, grad.indices],
[grad.values, momentum_data, param],
momentum=self.momentum,
nesterov=self.nesterov,
)
else:
net.ScatterWeightedSum(
[param, ONE, grad.indices, grad.values, lr], param
)
else:
if self.momentum > 0.0:
net.MomentumSGDUpdate(
[grad, momentum_data, lr, param],
[grad, momentum_data, param],
momentum=self.momentum,
nesterov=self.nesterov,
)
else:
coeff = lr
net.WeightedSum([param, ONE, grad, coeff], param)
def scale_learning_rate(self, scale):
self.base_learning_rate *= scale
return
class MultiPrecisionSgdOptimizer(SgdOptimizer):
def __init__(
self,
base_learning_rate=0.1,
momentum=0.0,
policy="fixed",
nesterov=True,
sparse_dedup_aggregator=None,
**kwargs
):
super().__init__(
base_learning_rate=base_learning_rate,
policy=policy,
momentum=momentum,
nesterov=nesterov,
sparse_dedup_aggregator=sparse_dedup_aggregator,
**kwargs
)
def _run(self, net, param_init_net, param_info):
param = param_info.blob
param_fp32 = (
param_info.blob_copy[core.DataType.FLOAT]
if param_info.blob_copy is not None
else None
)
# If we have a straight fp32 parameter, run the base class
if param_fp32 is None:
return SgdOptimizer._run(self, net, param_init_net, param_info)
grad = param_info.grad
if self.base_learning_rate == 0:
return
assert (
self.base_learning_rate > 0
), "Expect positive base learning rate, got {}".format(self.base_learning_rate)
lr, _ = self.build_lr(
net,
param_init_net,
base_learning_rate=-self.base_learning_rate,
policy=self.policy,
**(self.init_kwargs)
)
momentum_data = param_init_net.ConstantFill(
param_fp32, str(param) + "_momentum", value=0.0
)
self._aux_params.local.append(momentum_data)
assert not isinstance(
grad, core.GradientSlice
), "MultiPrecisionSgd does not support sparse gradients"
# Copy gradient to fp32
grad_fp32 = net.HalfToFloat(grad, grad + "_fp32")
# update (fused) in fp32
net.MomentumSGDUpdate(
[grad_fp32, momentum_data, lr, param_fp32],
[grad_fp32, momentum_data, param_fp32],
momentum=self.momentum,
nesterov=self.nesterov,
)
# Copy updated param back to fp16
net.FloatToHalf(param_fp32, param)
class FP16SgdOptimizer(SgdOptimizer):
def __init__(
self,
base_learning_rate=0.1,
momentum=0.0,
policy="fixed",
nesterov=True,
weight_decay=0.0001,
sparse_dedup_aggregator=None,
**kwargs
):
super().__init__(
base_learning_rate=base_learning_rate,
policy=policy,
momentum=momentum,
nesterov=nesterov,
sparse_dedup_aggregator=sparse_dedup_aggregator,
**kwargs
)
self.weight_decay = weight_decay
def _run(self, net, param_init_net, param_info, fp32_update=False):
fp32_update_flag = 0
param_name = str(param_info.blob)
# should only be triggered in FP16 training by SpatialBN, which
# requires FP32 params in CuDNN.
if param_name.find("spatbn") != -1:
fp32_update = True
if fp32_update:
# doing a 32bit update
# Have to assume param_info.blob is FP32 as there is no way
# (that i currently know of) to query a blob's type in python
fp32_update_flag = 1
param = param_info.blob
param_fp32 = param_info.blob
else:
if param_info.blob_copy is None:
# doing a 32bit update
# Have to assume param_info.blob is FP32 as there is no way
# (that i currently know of) to query a blob's type in python
fp32_update_flag = 1
param = param_info.blob
param_fp32 = param_info.blob
else:
if core.DataType.FLOAT in param_info.blob_copy:
param = param_info.blob
param_fp32 = param_info.blob_copy[core.DataType.FLOAT]
elif core.DataType.FLOAT16 in param_info.blob_copy:
param = param_info.blob_copy[core.DataType.FLOAT16]
param_fp32 = param_info.blob
else:
AssertionError(
"Unrecognized parameter format to be updated "
"by FP16 Optimizer. Parameter: {}".format(param_info.name)
)
grad = param_info.grad
if self.base_learning_rate == 0:
return
assert (
self.base_learning_rate > 0
), "Expect positive base learning rate, got {}".format(self.base_learning_rate)
lr, _ = self.build_lr(
net,
param_init_net,
base_learning_rate=-self.base_learning_rate,
policy=self.policy,
**(self.init_kwargs)
)
momentum_data_fp32 = param_init_net.ConstantFill(
param_fp32, str(param) + "_momentum_fp32", value=0.0
)
momentum_data = param_init_net.FloatToHalf(
momentum_data_fp32, str(param) + "_momentum"
)
self._aux_params.local.append(momentum_data)
assert not isinstance(
grad, core.GradientSlice
), "FP16Sgd does not support sparse gradients"
if fp32_update_flag == 0:
net.FP16MomentumSGDUpdate(
[grad, momentum_data, lr, param],
[grad, momentum_data, param],
momentum=self.momentum,
nesterov=self.nesterov,
weight_decay=self.weight_decay,
)
else:
# flag set to 1, therefore doing FP32 update
net.FP32MomentumSGDUpdate(
[grad, momentum_data_fp32, lr, param],
[grad, momentum_data_fp32, param],
momentum=self.momentum,
nesterov=self.nesterov,
weight_decay=self.weight_decay,
)
class WeightDecayBuilder(Optimizer):
def __init__(self, weight_decay):
self.weight_decay = weight_decay
def _run(self, net, param_init_net, param_info):
dev = scope.CurrentDeviceScope()
if dev is None:
dev = core.DeviceOption(caffe2_pb2.CPU)
ONE = param_init_net.ConstantFill(
[], "ONE_{}_{}".format(dev.device_type, dev.device_id), shape=[1], value=1.0
)
WD = param_init_net.ConstantFill(
[],
"wd_{}_{}".format(dev.device_type, dev.device_id),
shape=[1],
value=self.weight_decay,
)
if isinstance(param_info.grad, core.GradientSlice):
raise ValueError("Weight decay does not yet support sparse gradients")
else:
net.WeightedSum(
[param_info.grad, ONE, param_info.blob, WD], param_info.grad
)
class AdagradOptimizer(Optimizer):
def __init__(
self,
alpha=0.01,
epsilon=1e-4,
decay=1,
weight_decay=0.0,
policy="fixed",
sparse_dedup_aggregator=None,
rowWise=False,
engine="",
lars=None,
output_effective_lr=False,
output_effective_lr_and_update=False,
pruning_options=None,
swa_options=None,
ema_options=None,
weight_scale=None,
counter_halflife=-1,
use_dedicated_lr_iteration_counter=False,
**kwargs
):
super().__init__()
self.alpha = alpha
self.epsilon = epsilon
self.decay = decay
self.weight_decay = float(weight_decay)
self.policy = policy
self.sparse_dedup_aggregator = sparse_dedup_aggregator
self.rowWise = rowWise
self.engine = engine
self.lars = lars
self.output_effective_lr = output_effective_lr
self.output_effective_lr_and_update = output_effective_lr_and_update
self.counter_halflife = counter_halflife
self.init_kwargs = kwargs
self.weight_scale = weight_scale
self.use_dedicated_lr_iteration_counter = use_dedicated_lr_iteration_counter
self._process_pruning_options(pruning_options)
self._process_swa_options(swa_options)
self._process_ema_options(ema_options)
def set_mapping_for_param2ema_teacher_param(self, param_mapping: Dict[str, Any]) -> None:
self.param2ema_teacher_param = param_mapping
def _process_swa_options(self, swa_options):
self.swa_enabled = True if swa_options else False
if self.swa_enabled:
self.swa_avg_start_it = swa_options.get("swa_avg_start_it", None)
self.swa_avg_end_it = swa_options.get("swa_avg_end_it", None)
self.swa_feedback_start_it = swa_options.get("swa_feedback_start_it", None)
self.swa_feedback_step = swa_options.get("swa_feedback_step", None)
self.swa_feedback_end_it = swa_options.get("swa_feedback_end_it", None)
def _process_ema_options(self, ema_options):
logger.info(f"ema_options: {str(ema_options)}")
self.ema_enabled = ema_options and ema_options.get("ema_alpha", None) is not None
self.ema_teacher_enabled = ema_options and ema_options.get("ema_teacher_alpha", None) is not None
self.param2ema_teacher_param = {}
if self.ema_enabled or self.ema_teacher_enabled:
self.ema_start = ema_options.get("ema_start", None)
self.ema_end = ema_options.get("ema_end", None)
self.ema_step = ema_options.get("ema_step", None)
self.ema_alpha = ema_options.get("ema_alpha", None)
self.ema_teacher_alpha = ema_options.get("ema_teacher_alpha", None)
self.ema_teacher_module_name = ema_options.get(
"ema_teacher_module_name", "ema_teacher_arch"
)
def _process_pruning_options(self, pruning_options):
self.use_mask = False
if pruning_options is None:
pruning_options = {}
else:
assert isinstance(pruning_options, dict), (
"pruning_options can only "
"be provided as a dictionary, currently: {}".format(pruning_options)
)
self.mask_tensor = pruning_options.get("mask_tensor", None)
self.mask_db_path = pruning_options.get("mask_db_path", None)
self.mask_db_type = pruning_options.get("mask_db_type", None)
self.mask_blob_name = pruning_options.get("mask_blob_name", None)
self.prune_delays = pruning_options.get("prune_delays", [])
self.prune_ratios = pruning_options.get("prune_ratios", [])
self.prune_block_size = pruning_options.get("prune_block_size", 1)
if self.mask_tensor is not None:
assert (
type(self.mask_tensor) is np.ndarray
), "mask_tensor must be a numpy array!"
assert self.mask_db_path is None, (
"mask can be provided through either a numpy array "
"or a db path, not both"
)
assert self.mask_db_type is None, (
"mask can be provided through either a numpy array "
"or a db path, not both"
)
assert self.mask_blob_name is None, (
"mask can be provided through either a numpy array "
"or a db path, not both"
)
self.use_mask = True
if self.mask_db_path is not None or self.mask_db_type is not None:
assert self.mask_db_path is not None, (
"when mask is provided through db, "
"db path, db type, and blob name are all needed"
)
assert self.mask_db_type is not None, (
"when mask is provided through db, "
"db path, db type, and blob name are all needed"
)
assert self.mask_tensor is None, (
"mask can be provided through either a numpy array "
"or a db path, not both"
)
self.use_mask = True
if self.prune_delays:
assert self.prune_ratios is not None and len(self.prune_delays) == len(
self.prune_ratios
), "Prune Delays and prune ratios should be of the same length"
assert (
self.mask_tensor is None
), "Mask Tensor should be None with prune ratios"
assert (
self.mask_db_path is None
), "Mask DB Path should be None with prune ratios"
self.use_mask = True
def _run(self, net, param_init_net, param_info):
param = param_info.blob
grad = param_info.grad
if self.alpha <= 0:
return
self._clear_local_lr_multiplier()
if self.lars is not None and not isinstance(grad, core.GradientSlice):
assert (
self.weight_decay == 0
), "weight decay is not implemented for LARS yet"
assert self.lars >= 0, "Lars offset must be nonnegative, got {}".format(
self.lars
)
wd, trust, lr_max = self.create_lars_inputs(
param_init_net, 0.0, 1.0, np.finfo(np.float32).max
)
lr_lars_multiplier = net.Lars(
[param, grad, wd, trust, lr_max],
self.make_unique_blob_name(str(param) + "_lars"),
offset=self.lars,
lr_min=0.0,
)
current_scope = scope.CurrentDeviceScope()
self._add_local_lr_multiplier(
lr_lars_multiplier,
is_gpu_blob=(
current_scope is not None
and core.IsGPUDeviceType(current_scope.device_type)
),
)
lr, lr_iteration = self.build_lr(
net,
param_init_net,
base_learning_rate=self.alpha,
policy=self.policy,
**(self.init_kwargs)
)
iteration = (
self.build_non_lr_iter(net, param_init_net, iter_val=0)
if self._use_dedicated_lr_iteration_counter
else lr_iteration
)
if self.counter_halflife > 0:
self._aux_params.shared.append(iteration)
if self.rowWise:
logger.debug(
"Using engine {} for rowWise Adagrad to train param {}".format(
self.engine, param
)
)
shapes, types = workspace.InferShapesAndTypes([param_init_net])
if str(param) not in shapes:
# Type/shape inference is not available for this param, fallback
# on Shape/Slice logic
shape = param_init_net.Shape(param, str(param) + "_shape")
num_rows = param_init_net.Slice(
[shape], str(shape) + "_numrows", starts=[0], ends=[1]
)
param_squared_sum = param_init_net.ConstantFill(
num_rows,
str(param) + "_avg_squared_sum",
input_as_shape=1,
value=0.0,
)
else:
param_squared_sum = param_init_net.ConstantFill(
[],
str(param) + "_avg_squared_sum",
shape=[shapes[str(param)][0]],
value=0.0,
)
else:
logger.debug(
"Using engine {} for regular Adagrad to train param {}".format(
self.engine, param
)
)
if self.engine in FP16_ENGINES:
assert (
self.weight_decay == 0
), "weight decay is not tested for engine: {}".format(self.engine)
shapes, types = workspace.InferShapesAndTypes([param_init_net])
assert str(param) in shapes, shapes
shape = shapes[str(param)]
param_squared_sum = param_init_net.Float16ConstantFill(
[], str(param) + "_squared_sum", value=0.0, shape=shape
)
else:
param_squared_sum = param_init_net.ConstantFill(
[param], str(param) + "_squared_sum", value=0.0
)
if self.use_mask is True:
assert (
self.weight_decay == 0
), "weight decay is not implemented for use_mask yet"
if self.mask_tensor is not None:
if not isinstance(grad, core.GradientSlice):
mask_blob = param_init_net.GivenTensorFill(
[],
[str(param) + "_mask"],
values=self.mask_tensor,
shape=self.mask_tensor.shape,
)
else:
self.mask_tensor = self.mask_tensor.astype(np.uint8)
mask_blob = param_init_net.GivenTensorBoolFill(
[],
[str(param) + "_mask"],
values=self.mask_tensor,
shape=self.mask_tensor.shape,
)
mask_blob = param_init_net.Cast(mask_blob, to=core.DataType.UINT8)
mask_changed_blob = param_init_net.ConstantFill(
[],
[str(param) + "_mask_changed_blob"],
value=False,
dtype=core.DataType.BOOL,
shape=[1],
)
elif (
self.mask_db_path is not None or self.mask_db_type is not None
): # mask is provided through a db file
# if mask_blob_name is not given use the param name to derive mask name
self.mask_blob_name = self.mask_blob_name or str(param) + "_mask"
mask_blob = param_init_net.Load(
[],
self.mask_blob_name,
db=self.mask_db_path,
db_type=self.mask_db_type,
absolute_path=True,
)
if isinstance(grad, core.GradientSlice):
mask_changed_blob = param_init_net.ConstantFill(
[],
[str(param) + "_mask_changed_blob"],
value=False,
dtype=core.DataType.BOOL,
shape=[1],
)
elif self.prune_delays:
last_mask_updated_iter = param_init_net.ConstantFill(
[],
[str(param) + "_last_mask_updated_iter"],
value=-1,
dtype=core.DataType.INT64,
shape=[1],
)
if isinstance(grad, core.GradientSlice):
AssertionError(
"Prune Delays and Prune Ratios are currently not supported"
"for sparse operators"
)
else:
mask_blob = param_init_net.GivenTensorFill(
[],
[str(param) + "_empty_mask"],
values=[],
dtype=core.DataType.FLOAT,
shape=[0],
)
else:
raise NotImplementedError(
"If mask is used, it needs a numpy array or a db file or"
"a delay iter needs to be provided"
)
self._aux_params.local.append(param_squared_sum)
if self.counter_halflife > 0:
shapes, types = workspace.InferShapesAndTypes([param_init_net])
if str(param) not in shapes:
shape = param_init_net.Shape(param, str(param) + "_shape")
num_rows = param_init_net.Slice(
[shape], str(shape) + "_numrows", starts=[0], ends=[1]
)
update_counter = param_init_net.ConstantFill(
num_rows,
str(param) + "_update_counter",
input_as_shape=1,
value=0.0,
dtype=core.DataType.DOUBLE,
)
prev_update_iter = param_init_net.ConstantFill(
num_rows,
str(param) + "_prev_update_iter",
input_as_shape=1,
value=0,
dtype=core.DataType.INT64,
)
else:
update_counter = param_init_net.ConstantFill(
[],
str(param) + "_update_counter",
shape=[shapes[str(param)][0]],
value=0.0,
dtype=core.DataType.DOUBLE,
)
prev_update_iter = param_init_net.ConstantFill(
[],
str(param) + "_prev_update_iter",
shape=[shapes[str(param)][0]],
value=0,
dtype=core.DataType.INT64,
)
self._aux_params.local.append(update_counter)
self._aux_params.local.append(prev_update_iter)
if self.rowWise:
assert isinstance(grad, core.GradientSlice), (
"If SparseAdagrad with rowWise=True, gradient must be "
"a gradientslice. PLease ensure that rowWise is not enabled "
"for the dense Adagrad optimizer, as it is not supported."
)
shapes, _ = workspace.InferShapesAndTypes([param_init_net])
param_shape = shapes[str(param)]
weight_decay = 0.0
if isinstance(grad, core.GradientSlice):
if len(param_shape) == 1:
weight_decay = 0.0
logger.warn(
"SKIPPING weight decay on 1d sparse param: {}.shape is {}".format(
str(param), param_shape
)
)
else:
weight_decay = self.weight_decay
else:
# Skip weight decay for 1d parameters
if len(param_shape) == 1:
weight_decay = 0.0
logger.warning(
"SKIPPING weight decay on 1d dense param: {}.shape is {}".format(
str(param), param_shape
)
)