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