Llama开源代码详细解读(3)

expand_mask模块

python 复制代码
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
    """
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    """
    bsz, src_len = mask.size()
    tgt_len = tgt_len if tgt_len is not None else src_len

    expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)

    inverted_mask = 1.0 - expanded_mask

    return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)

这个函数接收一个张量mask,并将其变换为特定的形状。输入三个参数分别为:mask:大小为[bsz, seq_len]。dtype:数据类型。tgt_len:目标序列长度。以下是函数的运行方式。

获取mask参数

python 复制代码
  bsz, src_len = mask.size()
  • .size()函数获取了mask张量的行数、列数,即bsz,src_len。

确定目标序列长度

python 复制代码
tgt_len = tgt_len if tgt_len is not None else src_len
  • 如果tgt_len没有被指定,则赋值为src_len。

扩展掩码

python 复制代码
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
  • mask[:, None, None, :]将mask的维度从[bsz, seq_len]拓展为[bsz,1,1,seq_len],expand(bsz, 1, tgt_len, src_len)将拓展后的矩阵继续拓展为[bsz,1,tgt_len,src_len),to(dtype)转换为指定的数据类型。

生成反转掩码

python 复制代码
inverted_mask = 1.0 - expanded_mask

将掩码中0和1的位置互换。

填充反转掩码

python 复制代码
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)

inverted_mask.to(torch.bool)将反转掩码转换为布尔类型

masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)用dtype这个类型的最小值填充其中为true的位置。

返回一个经过填充处理的反转掩码张量,形状为 [bsz, 1, tgt_len, src_len],数据类型为 dtype。

RMSNorm归一化模块

python 复制代码
class LlamaRMSNorm(nn.Module):
    def __init__(self, hidden_size, eps=1e-6):
        # eps一个很小的数,用于避免除零错误
        """
        LlamaRMSNorm is equivalent to T5LayerNorm
        """
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        # weight是一个可训练的参数,初始化为一个大小为 hidden_size 的全 1 张量
        self.variance_epsilon = eps

    def forward(self, hidden_states):
        input_dtype = hidden_states.dtype
        # 存储hidden_states的数据类型
        hidden_states = hidden_states.to(torch.float32)
        variance = hidden_states.pow(2).mean(-1, keepdim=True)
        # hidden_states一般是batch size * sequence length * hidden size,这里的mean是按最后一维取平均
        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
        return (self.weight * hidden_states).to(input_dtype)

这段代码定义了一个RMSNorm类,用于实现归一化。

构造函数__init__()

python 复制代码
def __init__(self, hidden_size, eps=1e-6):
    super().__init__()
    self.weight = nn.Parameter(torch.ones(hidden_size))
    self.variance_epsilon = eps
  • hidden_size表示隐藏层的维度大小,eps表示一个很小的数,用于防止除零错误,self.weight表示为一个可训练的权重参数,初始化为一个和hidden_size大小一致的全1张量。

前向传播forward()

python 复制代码
def forward(self, hidden_states):
    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 + self.variance_epsilon)
    return (self.weight * hidden_states).to(input_dtype)
  • input_dtype储存隐藏层的数据类型
  • hidden_states = hidden_states.to(torch.float32)将数据类型转换为bf32,确保计算的稳定性
  • variance = hidden_states.pow(2).mean(-1, keepdim=True)计算隐藏层在最后一层的方差,具体步骤是对每个元素平方再取平均。
  • hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)计算反向标准差(1/标准差),并与hidden_state元素逐个相乘,从而实现归一化。
  • return (self.weight * hidden_states).to(input_dtype)将归一化后的隐藏层乘以权重,并转换回输入的数据类型。
相关推荐
u0109147601 天前
CSS组件库如何快速扩展_通过Sass @extend继承基础布局
jvm·数据库·python
baidu_340998821 天前
Golang怎么用go-noescape优化性能_Golang如何使用编译器指令控制逃逸分析行为【进阶】
jvm·数据库·python
m0_678485451 天前
如何利用虚拟 DOM 实现无痕刷新?基于 VNode 对比的状态保持技巧
jvm·数据库·python
qq_342295821 天前
CSS如何实现透明背景效果_通过RGBA色彩模式控制透明度
jvm·数据库·python
TechWayfarer1 天前
知乎/微博的IP属地显示为什么偶尔错误?用IP归属地查询平台自检工具3步验证
网络·python·网络协议·tcp/ip·网络安全
Greyson11 天前
CSS如何处理超长文本换行问题_结合word-wrap属性
jvm·数据库·python
justjinji1 天前
如何批量更新SQL数据表_使用UPDATE JOIN语法提升效率
jvm·数据库·python
小江的记录本1 天前
【网络安全】《网络安全常见攻击与防御》(附:《六大攻击核心特性横向对比表》)
java·网络·人工智能·后端·python·安全·web安全
贵沫末1 天前
python——打包自己的库并安装
开发语言·windows·python
思绪无限1 天前
YOLOv5至YOLOv12升级:植物叶片病害识别系统的设计与实现(完整代码+界面+数据集项目)
深度学习·yolo·目标检测·yolov12·yolo全家桶·植物叶片病害检测