Construct a stochastic gradient descent or ADAM optimizer with momentum. Details can be found in: Herbert Robbins, and Sutton Monro. "A stochastic approximation method." and Diederik P.Kingma, and Jimmy Ba. "Adam: A Method for Stochastic Optimization." Args: mod
(model, cfg)
| 12 | |
| 13 | |
| 14 | def construct_optimizer(model, cfg): |
| 15 | """ |
| 16 | Construct a stochastic gradient descent or ADAM optimizer with momentum. |
| 17 | Details can be found in: |
| 18 | Herbert Robbins, and Sutton Monro. "A stochastic approximation method." |
| 19 | and |
| 20 | Diederik P.Kingma, and Jimmy Ba. |
| 21 | "Adam: A Method for Stochastic Optimization." |
| 22 | |
| 23 | Args: |
| 24 | model (model): model to perform stochastic gradient descent |
| 25 | optimization or ADAM optimization. |
| 26 | cfg (config): configs of hyper-parameters of SGD or ADAM, includes base |
| 27 | learning rate, momentum, weight_decay, dampening, and etc. |
| 28 | """ |
| 29 | bn_parameters = [] |
| 30 | non_bn_parameters = [] |
| 31 | zero_parameters = [] |
| 32 | skip = {} |
| 33 | if hasattr(model, "no_weight_decay"): |
| 34 | skip = model.no_weight_decay() |
| 35 | |
| 36 | total_num = 0 |
| 37 | for name, m in model.named_modules(): |
| 38 | is_bn = isinstance(m, torch.nn.modules.batchnorm._NormBase) |
| 39 | for p in m.parameters(recurse=False): |
| 40 | if not p.requires_grad: |
| 41 | continue |
| 42 | total_num += 1 |
| 43 | if is_bn: |
| 44 | bn_parameters.append(p) |
| 45 | elif name in skip or ( |
| 46 | (len(p.shape) == 1 or name.endswith(".bias")) |
| 47 | and cfg.SOLVER.ZERO_WD_1D_PARAM |
| 48 | ): |
| 49 | zero_parameters.append(p) |
| 50 | else: |
| 51 | non_bn_parameters.append(p) |
| 52 | |
| 53 | optim_params = [ |
| 54 | {"params": bn_parameters, "weight_decay": cfg.BN.WEIGHT_DECAY}, |
| 55 | {"params": non_bn_parameters, "weight_decay": cfg.SOLVER.WEIGHT_DECAY}, |
| 56 | {"params": zero_parameters, "weight_decay": 0.0}, |
| 57 | ] |
| 58 | optim_params = [x for x in optim_params if len(x["params"])] |
| 59 | |
| 60 | # Check all parameters will be passed into optimizer. |
| 61 | assert total_num == len(non_bn_parameters) + len( |
| 62 | bn_parameters |
| 63 | ) + len( |
| 64 | zero_parameters |
| 65 | ), "parameter size does not match: {} + {} + {} != {}".format( |
| 66 | len(non_bn_parameters), |
| 67 | len(bn_parameters), |
| 68 | len(zero_parameters), |
| 69 | total_num, |
| 70 | ) |
| 71 | logger.info( |
nothing calls this directly
no test coverage detected