第四章:大模型(LLM)

第九部分:最强开源大模型:Llama3 原理介绍与实现

第一节:词 Embeddings 和 Rotary Positional Embeddings


1. 词 Embeddings(Token Embeddings)

1.1 概念
  • 词 Embeddings 是将离散的文本 token 映射为连续向量的方式,用于让模型理解文本语义。

  • 在 Llama3 中,每个 token 被映射到一个 d 维向量空间(通常 d = 4096 ~ 8192,视模型大小而定)。

  • Embedding 矩阵 E \in \mathbb{R}^{V \times d},其中 V 为词表大小。

1.2 作用
  • 将离散文本转换为连续表示,以便 Transformer 可以进行矩阵运算。

  • 提供 token 的语义信息,使模型能够捕捉词义、上下文关系。

1.3 实现方式

在 PyTorch 中,词 Embeddings 通常定义如下:

import torch
import torch.nn as nn

vocab_size = 32000  # 词表大小
embedding_dim = 4096  # 向量维度

token_embeddings = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)

# 假设输入 token id 序列
input_ids = torch.tensor([1, 23, 456, 7890])
embedded_tokens = token_embeddings(input_ids)  # 输出 shape: [batch, seq_len, embedding_dim]

2. Positional Embeddings 与 Rotary Positional Embeddings(RoPE)

2.1 Transformer 的位置编码问题
  • Transformer 自身不包含序列顺序信息,必须通过 位置编码(Positional Encoding)引入 token 的位置信息。

  • 传统做法:绝对位置编码(Sinusoidal PE 或可训练 PE),直接加到 token Embedding 上。

  • Llama3 使用 Rotary Positional Embedding(RoPE),一种相对位置编码方式,能够增强长序列的表示能力。

2.2 RoPE 原理

  • RoPE 将位置信息直接作用在 query 和 key 向量 上,通过旋转矩阵将序列位置信息编码到向量的角度中。

  • 对每个维度(通常以复数形式表示):

\begin{bmatrix} q_{2i} \\ q_{2i+1} \end{bmatrix} \mapsto \begin{bmatrix} \cos(\theta_i) & -\sin(\theta_i) \\ \sin(\theta_i) & \cos(\theta_i) \end{bmatrix} \begin{bmatrix} q_{2i} \\ q_{2i+1} \end{bmatrix}

  • 其中 \theta_i = 10000^{-2i/d}\cdot pos,pos 为 token 位置,d 为向量维度。

2.3 RoPE 优势
  1. 相对位置感知:可以自然捕捉序列之间的相对距离。

  2. 支持长序列推理:不依赖固定长度的绝对位置编码,适合长文本。

  3. 无需额外参数:通过旋转矩阵计算,无需训练额外的参数。

2.4 Llama3 中实现示例(PyTorch)
import torch
import math

def apply_rope(q, seq_len):
    """
    q: [batch, seq_len, n_heads, head_dim]
    """
    batch, seq_len, n_heads, head_dim = q.shape
    position_ids = torch.arange(seq_len, dtype=torch.float32, device=q.device)
    dim = head_dim // 2
    theta = 1.0 / (10000 ** (torch.arange(0, dim, 1.0, device=q.device) / dim))
    
    # position × θ
    angles = position_ids[:, None] * theta[None, :]
    
    # 生成 cos 和 sin
    cos = torch.cos(angles)
    sin = torch.sin(angles)
    
    q1 = q[..., ::2]
    q2 = q[..., 1::2]
    
    q_rotated = torch.stack([q1 * cos - q2 * sin, q1 * sin + q2 * cos], dim=-1)
    q_rotated = q_rotated.flatten(-2)  # 合并最后两个维度
    return q_rotated

# 示例:
batch, seq_len, n_heads, head_dim = 2, 8, 16, 64
q = torch.randn(batch, seq_len, n_heads, head_dim)
q_rope = apply_rope(q, seq_len)

3. 总结

  • 词 Embeddings:将离散 token 映射到连续向量空间,是模型理解文本语义的基础。

  • Rotary Positional Embeddings (RoPE):在 query 和 key 上施加旋转位置编码,引入相对位置信息,增强长序列建模能力。

  • Llama3 通过结合 高维 Embeddings + RoPE 支持高效、准确的长文本理解和推理。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐