Root Mean Square Layer Normalization.
| 4 | |
| 5 | |
| 6 | class RMSNorm(nn.Module): |
| 7 | """Root Mean Square Layer Normalization.""" |
| 8 | |
| 9 | def __init__(self, dim: int, eps: float = 1e-5): |
| 10 | super().__init__() |
| 11 | self.weight = nn.Parameter(torch.ones(dim)) |
| 12 | self.eps = eps |
| 13 | |
| 14 | def reset_parameters(self) -> None: |
| 15 | nn.init.constant_(self.weight, 1) |
| 16 | |
| 17 | def _norm(self, x: Tensor) -> Tensor: |
| 18 | return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) |
| 19 | |
| 20 | def forward(self, x: Tensor) -> Tensor: |
| 21 | output = self._norm(x.float()).type_as(x) |
| 22 | return output * self.weight |
| 23 | |
| 24 | |
| 25 | class LayerNorm(nn.LayerNorm): |