【大模型手撕】pytorch实现LayerNorm, RMSNorm

LayerNorm介绍请参考:【AI知识】归一化、批量归一化 、 层归一化 和 实例归一化

RMSNorm介绍请参考:【大模型知识点】RMSNorm(Root Mean Square Normalization)均方根归一化

LayerNorm实现:

python 复制代码
import torch 
import torch.nn as nn


class LayerNorm(nn.Module):
    def __init__(self,dim,eps=1e-5,bias=False):
        super().__init__()
        self.dim = dim
        self.eps = eps
        # 可训练的缩放参数
        self.gamma = nn.Parameter(torch.ones(dim))

        self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
    
    def forward(self,x):
        # x: (batch_size,seq_len,dim)
        # 计算均值 x_mean : (batch_size,seq_len,dim)
        x_mean = x.mean(-1,keepdim=True)
        # 计算均方根 rms :  (batch_size,seq_len,dim)
        rms = torch.sqrt(x.pow(2).mean(-1,keepdim=True)+self.eps)

        if self.bias:
            return self.gamma*((x-x_mean)/rms)+self.bias
        else:
            return self.gamma*((x-x_mean)/rms)

RMSNorm实现:

python 复制代码
import torch 
import torch.nn as nn

class RMSNorm(nn.Module):
    def __init__(self,dim,eps=1e-5,bias=False):
   		super().__init__()
        self.dim = dim 
        self.eps = eps
        # 可训练的缩放参数
        self.gamma = nn.Parameter(torch.ones(dim))
        self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
    def forward(self,x):
        # 计算输入的均方根
        # x: (batch_size,seq_len,dim)
        # .mean(-1,keepdim=True) : 在最后一个维度(特征维度)上计算平均值,并保持维度不变
        # rms : (batch_size,seq_len,1)
        rms = torch.sqrt(x.pow(2).mean(-1,keepdim=True)+self.eps)

        if self.bias:
            return self.gamma*(x/rms) + self.bias
        else:
            return self.gamma*(x/rms)
相关推荐
我的世界伊若28 分钟前
AI重塑IT职场:挑战与机遇并存
人工智能
lapiii35831 分钟前
[智能体设计模式] 第4章:反思(Reflection)
人工智能·python·设计模式
快乐非自愿1 小时前
Java垃圾收集器全解:从Serial到G1的进化之旅
java·开发语言·python
IT_Beijing_BIT3 小时前
tensorflow 图像分类 之四
人工智能·分类·tensorflow
卡奥斯开源社区官方4 小时前
NVIDIA Blackwell架构深度解析:2080亿晶体管如何重构AI算力规则?
人工智能·重构·架构
百锦再4 小时前
第11章 泛型、trait与生命周期
android·网络·人工智能·python·golang·rust·go
zbhbbedp282793cl6 小时前
如何在VSCode中安装Python扩展?
ide·vscode·python
数新网络7 小时前
The Life of a Read/Write Query for Apache Iceberg Tables
人工智能·apache·知识图谱
Yangy_Jiaojiao7 小时前
开源视觉-语言-动作(VLA)机器人项目全景图(截至 2025 年)
人工智能·机器人
gorgeous(๑>؂<๑)8 小时前
【ICLR26匿名投稿】OneTrackerV2:统一多模态目标跟踪的“通才”模型
人工智能·机器学习·计算机视觉·目标跟踪