luxfer / runtime /layers /normalization.py
mdxss's picture
Publish Luxfer early beta with runnable weights and language metadata
7b6f2cc verified
Raw History Blame Contribute Delete
1.98 kB
# Derived from PFN PLaMo; see docs/LICENSING.md.
import enum
import math
import warnings
from typing import Any, Dict, List, Literal, NamedTuple, Optional, Tuple, Union
import torch
from torch import nn
from torch.nn import functional as F
from transformers import GenerationMixin, PretrainedConfig, PreTrainedModel
from transformers.cache_utils import DynamicCache
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
def _plamo3_rms_norm(
hidden_states: torch.Tensor, weight: Optional[torch.Tensor], eps: float, offset: float = 1.0
) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + eps)
hidden_states = hidden_states.to(input_dtype)
if weight is not None:
hidden_states = (offset + weight) * hidden_states
return hidden_states
class LuxferRMSNorm(nn.Module):
"""
Note:
This is a customized RMSNorm used in PLaMo-2/3.
An explicit offset (e.g. 1.0) is added to the weight during forward,
so its behavior differs from torch.nn.RMSNorm, especially under weight decay.
For inference-only replacement with torch.nn.RMSNorm,
the offset must be folded into the weight (weight += offset).
"""
def __init__(
self,
hidden_size: int,
eps: float = 1e-6,
offset: float = 1.0,
device: Optional[Union[torch.device, str]] = None,
) -> None:
super().__init__()
self.weight = nn.Parameter(torch.zeros(hidden_size, device=device))
self.variance_epsilon = eps
self.offset = offset
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return _plamo3_rms_norm(hidden_states, self.weight, self.variance_epsilon, offset=self.offset)
# Legacy source aliases; canonical public names use Luxfer.
Plamo3RMSNorm = LuxferRMSNorm