Haidass-Image-Instruct / runtime /normalization.py
creegon's picture
Haidass-Image-Instruct 0.0.1 preview
6c912a9 verified
Raw History Blame Contribute Delete
916 Bytes
"""RMS normalization with device-specific dispatch."""
import torch
from torch import nn
class RMSNorm(nn.Module):
def __init__(self, dim, eps):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.eps = eps
def forward(self, hidden_states):
low_precision_weight = self.weight.dtype in (torch.float16, torch.bfloat16)
if hidden_states.device.type == 'npu':
import torch_npu
if low_precision_weight:
hidden_states = hidden_states.to(self.weight.dtype)
return torch_npu.npu_rms_norm(hidden_states, self.weight, epsilon=self.eps)[0]
variance = hidden_states.float().pow(2).mean(-1, keepdim=True)
normalized = hidden_states * torch.rsqrt(variance+self.eps)
if low_precision_weight:
normalized = normalized.to(self.weight.dtype)
return normalized*self.weight