| 8 | warnings.warn("Cannot import apex RMSNorm, switch to vanilla implementation") |
| 9 | |
| 10 | class RMSNorm(torch.nn.Module): |
| 11 | def __init__(self, dim: int, eps: float = 1e-6): |
| 12 | """ |
| 13 | Initialize the RMSNorm normalization layer. |
| 14 | |
| 15 | Args: |
| 16 | dim (int): The dimension of the input tensor. |
| 17 | eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6. |
| 18 | |
| 19 | Attributes: |
| 20 | eps (float): A small value added to the denominator for numerical stability. |
| 21 | weight (nn.Parameter): Learnable scaling parameter. |
| 22 | |
| 23 | """ |
| 24 | super().__init__() |
| 25 | self.eps = eps |
| 26 | self.weight = nn.Parameter(torch.ones(dim)) |
| 27 | |
| 28 | def _norm(self, x): |
| 29 | """ |
| 30 | Apply the RMSNorm normalization to the input tensor. |
| 31 | |
| 32 | Args: |
| 33 | x (torch.Tensor): The input tensor. |
| 34 | |
| 35 | Returns: |
| 36 | torch.Tensor: The normalized tensor. |
| 37 | |
| 38 | """ |
| 39 | return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) |
| 40 | |
| 41 | def forward(self, x): |
| 42 | """ |
| 43 | Forward pass through the RMSNorm layer. |
| 44 | |
| 45 | Args: |
| 46 | x (torch.Tensor): The input tensor. |
| 47 | |
| 48 | Returns: |
| 49 | torch.Tensor: The output tensor after applying RMSNorm. |
| 50 | |
| 51 | """ |
| 52 | output = self._norm(x.float()).type_as(x) |
| 53 | return output * self.weight |
| 54 | |
| 55 | |
| 56 |
no outgoing calls
no test coverage detected