MCPcopy Create free account
hub / github.com/VCIP-RGBD/DFormer / configure_optimizers

Function configure_optimizers

utils/init_func.py:72–149  ·  view source on GitHub ↗

This long function is unfortunately doing something very simple and is being very defensive: We are separating out all parameters of the model into two buckets: those that will experience weight decay for regularization and those that won't (biases, and layernorm/embedding weights).

(model, lr, weight_decay)

Source from the content-addressed store, hash-verified

70
71
72def configure_optimizers(model, lr, weight_decay):
73 """
74 This long function is unfortunately doing something very simple and is being very defensive:
75 We are separating out all parameters of the model into two buckets: those that will experience
76 weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
77 We are then returning the PyTorch optimizer object.
78 """
79
80 # separate out all parameters to those that will and won't experience regularizing weight decay
81 decay = set()
82 no_decay = set()
83 whitelist_weight_modules = (
84 torch.nn.Linear,
85 nn.Conv1d,
86 nn.Conv2d,
87 nn.Conv3d,
88 nn.ConvTranspose2d,
89 nn.ConvTranspose3d,
90 )
91 blacklist_weight_modules = (
92 torch.nn.LayerNorm,
93 torch.nn.Embedding,
94 nn.BatchNorm1d,
95 nn.BatchNorm2d,
96 nn.BatchNorm3d,
97 nn.GroupNorm,
98 nn.SyncBatchNorm,
99 LayerNorm,
100 nn.LazyBatchNorm1d,
101 nn.LazyBatchNorm2d,
102 nn.LazyBatchNorm3d,
103 )
104 for mn, m in model.named_modules():
105 for pn, p in m.named_parameters():
106 fpn = "%s.%s" % (mn, pn) if mn else pn # full param name
107
108 if pn.endswith("bias"):
109 # all biases will not be decayed
110 no_decay.add(fpn)
111 elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules):
112 # weights of whitelist modules will be weight decayed
113 decay.add(fpn)
114 elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules):
115 # weights of blacklist modules will NOT be weight decayed
116 no_decay.add(fpn)
117 elif "layer_scale" in fpn:
118 # special case layer norm scaling parameters in the T5 model
119 decay.add(fpn)
120 elif "depth_scale" in fpn:
121 # special case depth norm scaling parameters in the T5 model
122 no_decay.add(fpn)
123
124 # special case the position embedding parameter in the root GPT module as not decayed
125 # no_decay.add("pos_emb")
126
127 # validate that we considered every parameter
128 param_dict = {pn: p for pn, p in model.named_parameters()}
129 inter_params = decay & no_decay

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected