File size: 1,164 Bytes
df64241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import torch
import torch.nn as nn


class RMSNorm(nn.Module):
    """Root Mean Square normalization .

    Rescales each token vector to a stable magnitude, then applies a
    learned per-dimension gain. Cheaper than LayerNorm: no mean-centering.
    """

    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        # eps: tiny constant so we never divide by zero
        self.eps = eps
        # learned scale, one value per dimension; starts at 1 (no-op)
        self.weight = nn.Parameter(torch.ones(dim))

    def _norm(self, x: torch.Tensor) -> torch.Tensor:
        # rms = sqrt(mean(x^2)) computed over the last dim (the feature dim)
        # x * 1/rms  ->  rescales the vector to unit root-mean-square
        rms = torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
        return x * rms

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # normalize in float32 for numerical stability, then cast back
        # (input is bf16 during training; squaring bf16 loses precision)
        out = self._norm(x.float()).type_as(x)
        # apply the learned per-dimension gain
        return out * self.weight