(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
)
| 182 | |
| 183 | # https://github.com/huggingface/transformers/blob/c28d04e9e252a1a099944e325685f14d242ecdcd/src/transformers/models/gpt2/modeling_gpt2.py#L454 |
| 184 | def _init_weights( |
| 185 | module, |
| 186 | n_layer, |
| 187 | initializer_range=0.02, # Now only used for embedding layer. |
| 188 | rescale_prenorm_residual=True, |
| 189 | n_residuals_per_layer=1, # Change to 2 if we have MLP |
| 190 | ): |
| 191 | if isinstance(module, nn.Linear): |
| 192 | if module.bias is not None: |
| 193 | if not getattr(module.bias, "_no_reinit", False): |
| 194 | nn.init.zeros_(module.bias) |
| 195 | elif isinstance(module, nn.Embedding): |
| 196 | nn.init.normal_(module.weight, std=initializer_range) |
| 197 | |
| 198 | if rescale_prenorm_residual: |
| 199 | # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: |
| 200 | # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale |
| 201 | # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. |
| 202 | # > -- GPT-2 :: https://openai.com/blog/better-language-models/ |
| 203 | # |
| 204 | # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py |
| 205 | for name, p in module.named_parameters(): |
| 206 | if name in ["out_proj.weight", "fc2.weight"]: |
| 207 | # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block |
| 208 | # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) |
| 209 | # We need to reinit p since this code could be called multiple times |
| 210 | # Having just p *= scale would repeatedly scale it down |
| 211 | nn.init.kaiming_uniform_(p, a=math.sqrt(5)) |
| 212 | with torch.no_grad(): |
| 213 | p /= math.sqrt(n_residuals_per_layer * n_layer) |
| 214 | |
| 215 | |
| 216 | def segm_init_weights(m): |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…