MCPcopy Create free account
hub / github.com/UX-Decoder/Semantic-SAM / build_optimizer

Method build_optimizer

train_net.py:179–266  ·  view source on GitHub ↗
(cls, cfg, model)

Source from the content-addressed store, hash-verified

177
178 @classmethod
179 def build_optimizer(cls, cfg, model):
180 cfg_solver = cfg['SOLVER']
181 weight_decay_norm = cfg_solver['WEIGHT_DECAY_NORM']
182 weight_decay_embed = cfg_solver['WEIGHT_DECAY_EMBED']
183 weight_decay_bias = cfg_solver.get('WEIGHT_DECAY_BIAS', 0.0)
184
185 defaults = {}
186 defaults["lr"] = cfg_solver['BASE_LR']
187 defaults["weight_decay"] = cfg_solver['WEIGHT_DECAY']
188
189 norm_module_types = (
190 torch.nn.BatchNorm1d,
191 torch.nn.BatchNorm2d,
192 torch.nn.BatchNorm3d,
193 torch.nn.SyncBatchNorm,
194 # NaiveSyncBatchNorm inherits from BatchNorm2d
195 torch.nn.GroupNorm,
196 torch.nn.InstanceNorm1d,
197 torch.nn.InstanceNorm2d,
198 torch.nn.InstanceNorm3d,
199 torch.nn.LayerNorm,
200 torch.nn.LocalResponseNorm,
201 )
202
203 lr_multiplier = cfg['SOLVER']['LR_MULTIPLIER']
204
205 params: List[Dict[str, Any]] = []
206 memo: Set[torch.nn.parameter.Parameter] = set()
207 for module_name, module in model.named_modules():
208 for module_param_name, value in module.named_parameters(recurse=False):
209 if not value.requires_grad:
210 continue
211 # Avoid duplicating parameters
212 if value in memo:
213 continue
214 memo.add(value)
215
216 hyperparams = copy.copy(defaults)
217
218 for key, lr_mul in lr_multiplier.items():
219 if key in "{}.{}".format(module_name, module_param_name):
220 hyperparams["lr"] = hyperparams["lr"] * lr_mul
221 if comm.is_main_process():
222 logger.info("Modify Learning rate of {}: {}".format(
223 "{}.{}".format(module_name, module_param_name), lr_mul))
224
225 if (
226 "relative_position_bias_table" in module_param_name
227 or "absolute_pos_embed" in module_param_name
228 ):
229 hyperparams["weight_decay"] = 0.0
230 if isinstance(module, norm_module_types):
231 hyperparams["weight_decay"] = weight_decay_norm
232 if isinstance(module, torch.nn.Embedding):
233 hyperparams["weight_decay"] = weight_decay_embed
234 if "bias" in module_name:
235 hyperparams["weight_decay"] = weight_decay_bias
236 params.append({"params": [value], **hyperparams})

Callers 1

__init__Method · 0.95

Calls 2

itemsMethod · 0.80

Tested by

no test coverage detected