Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

optimizer_utils.py 5.5 KB

You have to be logged in to leave a comment. Sign In
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
  1. import torch.optim as optim
  2. import torch.nn as nn
  3. from torch.nn.modules.batchnorm import _BatchNorm
  4. from torch.nn.modules.conv import _ConvNd
  5. from super_gradients.common.abstractions.abstract_logger import get_logger
  6. from super_gradients.training.params import DEFAULT_OPTIMIZER_PARAMS_SGD, DEFAULT_OPTIMIZER_PARAMS_ADAM, \
  7. DEFAULT_OPTIMIZER_PARAMS_RMSPROP, DEFAULT_OPTIMIZER_PARAMS_RMSPROPTF
  8. from super_gradients.training.utils import get_param
  9. from super_gradients.training.utils.optimizers.rmsprop_tf import RMSpropTF
  10. logger = get_logger(__name__)
  11. OPTIMIZERS_DICT = {"SGD": {"class": optim.SGD, "params": DEFAULT_OPTIMIZER_PARAMS_SGD},
  12. "Adam": {"class": optim.Adam, "params": DEFAULT_OPTIMIZER_PARAMS_ADAM},
  13. "RMSprop": {"class": optim.RMSprop, "params": DEFAULT_OPTIMIZER_PARAMS_RMSPROP},
  14. "RMSpropTF": {"class": RMSpropTF, "params": DEFAULT_OPTIMIZER_PARAMS_RMSPROPTF}}
  15. def separate_zero_wd_params_groups_for_optimizer(module: nn.Module, net_named_params, weight_decay: float):
  16. """
  17. separate param groups for batchnorm and biases and others with weight decay. return list of param groups in format
  18. required by torch Optimizer classes.
  19. bias + BN with weight decay=0 and the rest with the given weight decay
  20. :param module: train net module.
  21. :param net_named_params: list of params groups, output of SgModule.initialize_param_groups
  22. :param weight_decay: value to set for the non BN and bias parameters
  23. """
  24. # FIXME - replace usage of ids addresses to find batchnorm and biases params.
  25. # This solution iterate 2 times over module parameters, find a way to iterate only one time.
  26. no_decay_ids = _get_no_decay_param_ids(module)
  27. # split param groups for optimizer
  28. optimizer_param_groups = []
  29. for param_group in net_named_params:
  30. no_decay_params = []
  31. decay_params = []
  32. for name, param in param_group["named_params"]:
  33. if id(param) in no_decay_ids:
  34. no_decay_params.append(param)
  35. else:
  36. decay_params.append(param)
  37. # append two param groups from the original param group, with and without weight decay.
  38. extra_optim_params = {key: param_group[key] for key in param_group
  39. if key not in ["named_params", "weight_decay"]}
  40. optimizer_param_groups.append({"params": no_decay_params, "weight_decay": 0.0, **extra_optim_params})
  41. optimizer_param_groups.append({"params": decay_params, "weight_decay": weight_decay, **extra_optim_params})
  42. return optimizer_param_groups
  43. def _get_no_decay_param_ids(module: nn.Module):
  44. # FIXME - replace usage of ids addresses to find batchnorm and biases params.
  45. # Use other common way to identify torch parameters other than id or layer names
  46. """
  47. Iterate over module.modules() and returns params id addresses of batch-norm and biases params.
  48. NOTE - ALL MODULES WITH ATTRIBUTES NAMED BIAS AND ARE INSTANCE OF nn.Parameter WILL BE CONSIDERED A BIAS PARAM FOR
  49. ZERO WEIGHT DECAY.
  50. """
  51. batchnorm_types = (_BatchNorm,)
  52. torch_weight_with_bias_types = (_ConvNd, nn.Linear)
  53. no_decay_ids = []
  54. for name, m in module.named_modules():
  55. if isinstance(m, batchnorm_types):
  56. no_decay_ids.append(id(m.weight))
  57. no_decay_ids.append(id(m.bias))
  58. elif hasattr(m, "bias") and isinstance(m.bias, nn.Parameter):
  59. if not isinstance(m, torch_weight_with_bias_types):
  60. logger.warning(f"Module class: {m.__class__}, have a `bias` parameter attribute but is not instance of"
  61. f" torch primitive modules, this bias parameter will be part of param group with zero"
  62. f" weight decay.")
  63. no_decay_ids.append(id(m.bias))
  64. return no_decay_ids
  65. def build_optimizer(net, lr, training_params):
  66. """
  67. Wrapper function for initializing the optimizer
  68. :param net: the nn_module to build the optimizer for
  69. :param lr: initial learning rate
  70. :param training_params: training_parameters
  71. """
  72. default_optimizer_params = OPTIMIZERS_DICT[training_params.optimizer]["params"]
  73. training_params.optimizer_params = get_param(training_params, 'optimizer_params', default_optimizer_params)
  74. # OPTIMIZER PARAM GROUPS ARE SET USING DEFAULT OR MODEL SPECIFIC INIT
  75. if hasattr(net.module, 'initialize_param_groups'):
  76. # INITIALIZE_PARAM_GROUPS MUST RETURN A LIST OF DICTS WITH 'named_params' AND OPTIMIZER's ATTRIBUTES PER GROUP
  77. net_named_params = net.module.initialize_param_groups(lr, training_params)
  78. else:
  79. net_named_params = [{'named_params': net.named_parameters()}]
  80. if training_params.zero_weight_decay_on_bias_and_bn:
  81. optimizer_training_params = separate_zero_wd_params_groups_for_optimizer(
  82. net.module, net_named_params, training_params.optimizer_params['weight_decay']
  83. )
  84. else:
  85. # Overwrite groups to include params instead of named params
  86. for ind_group, param_group in enumerate(net_named_params):
  87. param_group['params'] = [param[1] for param in list(param_group['named_params'])]
  88. del param_group['named_params']
  89. net_named_params[ind_group] = param_group
  90. optimizer_training_params = net_named_params
  91. # CREATE AN OPTIMIZER OBJECT AND INITIALIZE IT
  92. optimizer_cls = OPTIMIZERS_DICT[training_params.optimizer]["class"]
  93. optimizer = optimizer_cls(optimizer_training_params, lr=lr, **training_params.optimizer_params)
  94. return optimizer
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...