File size: 1,980 Bytes
7b6f2cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 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