(
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
)
| 510 | |
| 511 | |
| 512 | def _init_weights( |
| 513 | module, |
| 514 | n_layer, |
| 515 | initializer_range=0.02, # Now only used for embedding layer. |
| 516 | rescale_prenorm_residual=True, |
| 517 | n_residuals_per_layer=1, # Change to 2 if we have MLP |
| 518 | ): |
| 519 | if isinstance(module, nn.Linear): |
| 520 | if module.bias is not None: |
| 521 | if not getattr(module.bias, "_no_reinit", False): |
| 522 | nn.init.zeros_(module.bias) |
| 523 | elif isinstance(module, nn.Embedding): |
| 524 | nn.init.normal_(module.weight, std=initializer_range) |
| 525 | |
| 526 | if rescale_prenorm_residual: |
| 527 | # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: |
| 528 | # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale |
| 529 | # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. |
| 530 | # > -- GPT-2 :: https://openai.com/blog/better-language-models/ |
| 531 | # |
| 532 | # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py |
| 533 | for name, p in module.named_parameters(): |
| 534 | if name in ["out_proj.weight", "fc2.weight"]: |
| 535 | # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block |
| 536 | # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) |
| 537 | # We need to reinit p since this code could be called multiple times |
| 538 | # Having just p *= scale would repeatedly scale it down |
| 539 | nn.init.kaiming_uniform_(p, a=math.sqrt(5)) |
| 540 | with torch.no_grad(): |
| 541 | p /= math.sqrt(n_residuals_per_layer * n_layer) |
| 542 | |
| 543 | |
| 544 | class ZigMa(nn.Module): |
nothing calls this directly
no outgoing calls
no test coverage detected