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

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

Comments

Loading...