经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 大数据/云/AI » 人工智能基础 » 查看文章
LLaMA 3 源码解读-大语言模型5
来源:cnblogs  作者:vanilla阿草  时间:2024/5/8 9:11:49  对本文有异议

本来不是很想写这一篇,因为网上的文章真的烂大街了,我写的真的很有可能没别人写得好。但是想了想,创建这个博客就是想通过对外输出知识的方式来提高自身水平,而不是说我每篇都能写得有多好多好然后吸引别人来看。那作为对整个合集内容的完善,这篇博客会解析现在最火的LLaMA3的模型架构,搞清楚现在的LLM都是啥样的。

事先说明,LlaMA 3 相较于LLaMA 2 在网络架构上没有改进。用知乎网友的话说,“llama3的发布,更强调了数据工程的重要:模型架构不变,更多的数据量和更高数据质量能够带来明显模型效果提升”。但是仔细看看一个LLM的源码,对于我这种初学者,还是非常有必要的。

https://zhuanlan.zhihu.com/p/693428105

还有就是,这个博客解析的源码是d6e09315954d1a547bf45e37269978c049e73d33这个版本的。如果后面Meta更新的部分代码导致和这篇博客内容对不上,你可以先翻阅这个版本的源码。如果还有什么解决不了的,可以在这篇博客下面给我留言,我们共同学习共同进步。

Llama类:起步

Llama.build与如何看源码

我们通过llama3的ReadMe,找到了这个demo,demo通过

  1. from llama import Dialog, Llama
  2. generator = (ckpt_dir, tokenizer_path, max_seq_len, max_batch_size)
  3. results = generator.chat_completion(dialogs, max_gen_len, temperature, top_p)

完成对话。它先调用了 Llama.build,再对返回的对象调用了generator.chat_completion完成对话的功能;导入的库是llama。 进而关注到repo下面的llama文件夹,所以会先看一看文件夹下面的__init__.py

  1. from .generation import Llama
  2. from .model import ModelArgs, Transformer
  3. from .tokenizer import Dialog, Tokenizer

所以demo调用的 Llama.build.generation里面。顺藤摸瓜找到:

  1. class Llama:
  2. @staticmethod
  3. def build(
  4. ckpt_dir: str,
  5. tokenizer_path: str,
  6. max_seq_len: int,
  7. max_batch_size: int,
  8. model_parallel_size: Optional[int] = None,
  9. seed: int = 1,
  10. ) -> "Llama":
  11. """
  12. Build a Llama instance by initializing and loading a model checkpoint.
  13. Args:
  14. ckpt_dir (str): 模型检查点文件的路径
  15. tokenizer_path (str): 模型tokenizer文件路径.
  16. max_seq_len (int): Maximum sequence length for input text.
  17. max_batch_size (int): Maximum batch size for inference.
  18. model_parallel_size (Optional[int], optional): Number of model parallel processes.
  19. If not provided, it's determined from the environment. Defaults to None.
  20. Returns:
  21. Llama: An instance of the Llama class with the loaded model and tokenizer.
  22. """
  23. # 这里首先是一些模型并行设置
  24. if not torch.distributed.is_initialized():
  25. torch.distributed.init_process_group("nccl")
  26. if not model_parallel_is_initialized():
  27. if model_parallel_size is None:
  28. model_parallel_size = int(os.environ.get("WORLD_SIZE", 1))
  29. initialize_model_parallel(model_parallel_size)
  30. # 多机训练/推理一个模型的话,每个机器都会有个rank。这里就是配置这个rank的。
  31. local_rank = int(os.environ.get("LOCAL_RANK", 0))
  32. torch.cuda.set_device(local_rank)
  33. # 随机种子
  34. torch.manual_seed(seed)
  35. # 设置输出只在一台设备上进行
  36. if local_rank > 0:
  37. sys.stdout = open(os.devnull, "w")
  38. # 终于到加载模型相关的代码了
  39. start_time = time.time()
  40. checkpoints = sorted(Path(ckpt_dir).glob("*.pth"))
  41. # 检查模型检查点文件的数量是否合乎要求
  42. assert len(checkpoints) > 0, f"no checkpoint files found in {ckpt_dir}"
  43. assert model_parallel_size == len(
  44. checkpoints
  45. ), f"Loading a checkpoint for MP={len(checkpoints)} but world size is {model_parallel_size}"
  46. # 加载模型。多机运行时`get_model_parallel_rank()`返回的结果不一样,所以不需要写for循环。这里的思想有cuda编程那味了
  47. ckpt_path = checkpoints[get_model_parallel_rank()]
  48. checkpoint = torch.load(ckpt_path, map_location="cpu")
  49. # TODO: 读取`params.json`并通过类`ModelArgs`加载进变量`model_args`。这个类我们待会讲
  50. with open(Path(ckpt_dir) / "params.json", "r") as f:
  51. params = json.loads(f.read())
  52. model_args: ModelArgs = ModelArgs(
  53. max_seq_len=max_seq_len,
  54. max_batch_size=max_batch_size,
  55. **params,
  56. )
  57. # TODO: 加载Tokenizer。Tokenizer我们待会讲
  58. tokenizer = Tokenizer(model_path=tokenizer_path)
  59. assert model_args.vocab_size == tokenizer.n_words
  60. # 半精度相关
  61. if torch.cuda.is_bf16_supported():
  62. torch.set_default_tensor_type(torch.cuda.BFloat16Tensor)
  63. else:
  64. torch.set_default_tensor_type(torch.cuda.HalfTensor)
  65. # TODO: 是的,llama3的模型主体就是这里的Transformer类。直接model.load_state_dict就能加载好权重。这个也待会讲
  66. model = Transformer(model_args)
  67. model.load_state_dict(checkpoint, strict=False)
  68. print(f"Loaded in {time.time() - start_time:.2f} seconds")
  69. # TODO: 到这里其实啥都加载完了,这里返回了个Llama类。
  70. return Llama(model, tokenizer)

这段代码看下来逻辑很清晰,就是给我们留下了几个TODO,这些我们都会讲到。

ModelArgs

我们首先看到ModelArgs类,这个类只用于保存一些参数,@dataclass装饰器就已经说明了一切:

  1. @dataclass
  2. class ModelArgs:
  3. dim: int = 4096 # 模型维度
  4. n_layers: int = 32 # 层数
  5. n_heads: int = 32 # 头数
  6. n_kv_heads: Optional[int] = None
  7. vocab_size: int = -1 # 词汇表大小
  8. multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2
  9. ffn_dim_multiplier: Optional[float] = None
  10. norm_eps: float = 1e-5
  11. rope_theta: float = 500000
  12. max_batch_size: int = 32
  13. max_seq_len: int = 2048 # 序列长度

llama.__init__()

最后这一句return Llama(model, tokenizer),它实际上会调用Llama.__init__(),代码如下:

  1. from llama.tokenizer import ChatFormat, Dialog, Message, Tokenizer
  2. def __init__(self, model: Transformer, tokenizer: Tokenizer):
  3. self.model = model
  4. self.tokenizer = tokenizer
  5. # TODO: ChatFormat类解析
  6. self.formatter = ChatFormat(tokenizer)

是的,简单赋值就结束了。formatter这里用到的ChatFormat类我们一会随tokenizer一起解析。

Transformer类:Llama3模型架构详解

这一部分应该是被人关心得最多的部分了。

Transformer.__init__()

首先看模型初始化,这里就是设置了一堆类的属性。我们直接上代码,解析见代码注释:

  1. from fairscale.nn.model_parallel.layers import (
  2. ColumnParallelLinear,
  3. RowParallelLinear,
  4. VocabParallelEmbedding,
  5. ) # FairScale库的模块都是用于实现模型并行化的,不需要深究
  6. class Transformer(nn.Module):
  7. def __init__(self, params: ModelArgs):
  8. super().__init__()
  9. self.params = params
  10. self.vocab_size = params.vocab_size
  11. self.n_layers = params.n_layers
  12. # VocabParallelEmbedding类导入自fairscale,功能同`torch.nn.embedding`
  13. self.tok_embeddings = VocabParallelEmbedding(
  14. params.vocab_size, params.dim, init_method=lambda x: x
  15. )
  16. self.layers = torch.nn.ModuleList()
  17. for layer_id in range(params.n_layers):
  18. # TODO: TransformerBlock
  19. self.layers.append(TransformerBlock(layer_id, params))
  20. # TODO: RMSNorm
  21. self.norm = RMSNorm(params.dim, eps=params.norm_eps)
  22. # ColumnParallelLinear 相当于 `torch.nn.linear`
  23. self.output = ColumnParallelLinear(
  24. params.dim, params.vocab_size, bias=False, init_method=lambda x: x
  25. )
  26. # TODO: precompute_freqs_cis
  27. self.freqs_cis = precompute_freqs_cis(
  28. params.dim // params.n_heads,
  29. params.max_seq_len * 2,
  30. params.rope_theta,
  31. )

RMSNorm

RMSNorm是均值为0的LayerNorm:

\[\begin{equation} \bar{a}_i=\frac{a_i}{R M S(a)} g_i \text{ where } R M S(a)=\sqrt{\frac{1}{n} \sum_{i=1}^n a_i{ }^2} \end{equation} \]

注:layerNorm为

\[\begin{equation} \bar{a}_i=\frac{a_i - \mu }{ \sigma } g_i \text{ where } \mu=\frac{1}{n} \sum_{i=1}^n {a_i } \text{ and } \sigma=\sqrt{\frac{1}{n} \sum_{i=1}^n {(a_i - \mu)}^2} \end{equation}\]

用代码实现出来是这个样子的:

  1. class RMSNorm(torch.nn.Module):
  2. def __init__(self, dim: int, eps: float = 1e-6):
  3. super().__init__()
  4. self.eps = eps
  5. self.weight = nn.Parameter(torch.ones(dim)) # 初始化为1的可学习参数
  6. def _norm(self, x):
  7. # torch.rsqrt: 平方根的倒数,这里用于计算标准差的倒数
  8. # x.pow(2).mean(-1, keepdim=True): 沿着倒数第一维计算平方并求平均
  9. # a_i * 元素平方的均值取平方根后再取倒数 + 无穷小量
  10. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
  11. def forward(self, x):
  12. output = self._norm(x.float()).type_as(x)
  13. return output * self.weight

作者认为这种模式在简化了Layer Norm的同时,可以在各个模型上减少约 7%~64% 的计算时间

旋转位置编码RoPE

该部分内容参考了 苏剑成的博客。苏剑成是RoPE的发明者。

旋转位置编码通过绝对位置编码的方式实现相对位置编码。假设通过下述运算来给 \(q,k\) 添加绝对位置信息:

分别为 \(q,k\) 设计操作 \(\boldsymbol{f}(\cdot, m),\boldsymbol{f}(\cdot, n)\) ,使得经过该操作后,\(\tilde{\boldsymbol{q}}_m,\tilde{\boldsymbol{k}}_n\) 就带有了位置 \(m,n\) 的绝对位置信息。Attention的核心运算是内积,所以我们希望的内积的结果带有相对位置信息,因此假设存在恒等关系:

\[\begin{equation}\langle\boldsymbol{f}(\boldsymbol{q}, m), \boldsymbol{f}(\boldsymbol{k}, n)\rangle = g(\boldsymbol{q},\boldsymbol{k},m-n)\end{equation} \]

解得:

\[\begin{equation} \boldsymbol{f}(\boldsymbol{q}, m) = R_f (\boldsymbol{q}, m)e^{\text{i}\Theta_f(\boldsymbol{q}, m)} = \Vert q\Vert e^{\text{i}(\Theta(\boldsymbol{q}) + m\theta)} = \boldsymbol{q} e^{\text{i}m\theta}\end{equation} \]

可以写成:

\[\begin{equation} \boldsymbol{f}(\boldsymbol{q}, m) =\begin{pmatrix}\cos m\theta & -\sin m\theta\\ \sin m\theta & \cos m\theta\end{pmatrix} \begin{pmatrix}q_0 \\ q_1\end{pmatrix}\end{equation} \]

由于内积满足线性叠加性,因此任意偶数维的RoPE,我们都可以表示为二维情形的拼接,即:

\[\begin{equation}\scriptsize{\underbrace{\begin{pmatrix} \cos m\theta_0 & -\sin m\theta_0 & 0 & 0 & \cdots & 0 & 0 \\sin m\theta_0 & \cos m\theta_0 & 0 & 0 & \cdots & 0 & 0 \0 & 0 & \cos m\theta_1 & -\sin m\theta_1 & \cdots & 0 & 0 \0 & 0 & \sin m\theta_1 & \cos m\theta_1 & \cdots & 0 & 0 \\vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \0 & 0 & 0 & 0 & \cdots & \cos m\theta_{d/2-1} & -\sin m\theta_{d/2-1} \0 & 0 & 0 & 0 & \cdots & \sin m\theta_{d/2-1} & \cos m\theta_{d/2-1} \\end{pmatrix}}_{\boldsymbol{\mathcal{R}}_m} \begin{pmatrix}q_0 \\ q_1 \\ q_2 \\ q_3 \\ \vdots \\ q_{d-2} \\ q_{d-1}\end{pmatrix}}\end{equation} \]

我们便可以通过以下方式实现RoPE:

\[\begin{equation}\begin{pmatrix}q_0 \\ q_1 \\ q_2 \\ q_3 \\ \vdots \\ q_{d-2} \\ q_{d-1} \end{pmatrix}\otimes\begin{pmatrix}\cos m\theta_0 \\ \cos m\theta_0 \\ \cos m\theta_1 \\ \cos m\theta_1 \\ \vdots \\ \cos m\theta_{d/2-1} \\ \cos m\theta_{d/2-1} \end{pmatrix} + \begin{pmatrix}-q_1 \\ q_0 \\ -q_3 \\ q_2 \\ \vdots \\ -q_{d-1} \\ q_{d-2} \end{pmatrix}\otimes\begin{pmatrix}\sin m\theta_0 \\ \sin m\theta_0 \\ \sin m\theta_1 \\ \sin m\theta_1 \\ \vdots \\ \sin m\theta_{d/2-1} \\ \sin m\theta_{d/2-1} \end{pmatrix}\end{equation} \]

precompute_freqs_cis

  1. def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
  2. # 计算词向量元素两两分组以后,每组元素对应的旋转角度
  3. # torch.arange(0, dim, 2): 生成 [0,2,4...126]
  4. freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
  5. t = torch.arange(end, device=freqs.device, dtype=torch.float32) # t = [0,....end]
  6. # torch.outer: torch.outer(a, b) = a^T * b
  7. freqs = torch.outer(t, freqs) # freqs.shape = (t.len(),freqs.len()) #shape (end,dim//2)
  8. # 根据角坐标生成复数向量
  9. # torch.polar(abs,angle): abs*cos(angle) + abs*sin(angle)*j
  10. freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # freqs_cis.shape = (end,dim//2)
  11. return freqs_cis

reshape_for_broadcast

  1. def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
  2. # ndim为x的维度数, 此时应该为4
  3. ndim = x.ndim
  4. assert 0 <= 1 < ndim
  5. assert freqs_cis.shape == (x.shape[1], x.shape[-1])
  6. shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
  7. # (1, x.shape[1], 1, x.shape[-1])
  8. return freqs_cis.view(*shape)

apply_rotary_emb

  1. def apply_rotary_emb(
  2. xq: torch.Tensor,
  3. xk: torch.Tensor,
  4. freqs_cis: torch.Tensor,
  5. ) -> Tuple[torch.Tensor, torch.Tensor]:
  6. """将xq和xk的最后一个维度进行复数运算,得到新的xq和xk"""
  7. # xq.shape = [bsz, seqlen, self.n_local_heads, self.head_dim]
  8. # xq_.shape = [bsz, seqlen, self.n_local_heads, self.head_dim//2 , 2]
  9. # torch.view_as_complex用于将二维向量转换为复数域 torch.view_as_complex即([x,y]) -> (x+yj)
  10. # 所以经过view_as_complex变换后xq_.shape = [bsz, seqlen, self.n_local_heads, self.head_dim//2]
  11. xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
  12. xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
  13. freqs_cis = reshape_for_broadcast(freqs_cis, xq_) # freqs_cis.shape = (1,x.shape[1],1,x.shape[-1])
  14. # xq_ 与freqs_cis广播哈达玛积
  15. # [bsz, seqlen, self.n_local_heads, self.head_dim//2] * [1,seqlen,1,self.head_dim//2]
  16. # torch.view_as_real用于将复数再转换回实数向量, 再经过flatten展平第4个维度
  17. # [bsz, seqlen, self.n_local_heads, self.head_dim//2] ->[bsz, seqlen, self.n_local_heads, self.head_dim//2,2 ] ->[bsz, seqlen, self.n_local_heads, self.head_dim]
  18. xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
  19. xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
  20. return xq_out.type_as(xq), xk_out.type_as(xk)

TransformerBlock

这个类比较简单,只是一个transformer block。

  1. class TransformerBlock(nn.Module):
  2. def __init__(self, layer_id: int, args: ModelArgs):
  3. """初始化函数主要就是定义了transformer block的各个组件,包括自注意力机制和前馈神经网络。"""
  4. super().__init__()
  5. self.n_heads = args.n_heads
  6. self.dim = args.dim
  7. self.head_dim = args.dim // args.n_heads
  8. # TODO: Attention
  9. self.attention = Attention(args)
  10. # TODO: FeedForward
  11. self.feed_forward = FeedForward(
  12. dim=args.dim, hidden_dim=4 * args.dim, multiple_of=args.multiple_of, ffn_dim_multiplier=args.ffn_dim_multiplier,
  13. )
  14. self.layer_id = layer_id
  15. self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
  16. self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
  17. def forward(
  18. self,
  19. x: torch.Tensor,
  20. start_pos: int,
  21. freqs_cis: torch.Tensor,
  22. mask: Optional[torch.Tensor],
  23. ):
  24. """这个函数是transformer block的前向传播函数,输入是x,start_pos,freqs_cis,mask,输出是out"""
  25. # 这个函数的实现比较简单,首先对输入张量x进行自注意力机制计算,然后对计算结果进行残差连接和归一化,再通过前馈神经网络计算,最后再次进行残差连接和归一化。
  26. h = x + self.attention(self.attention_norm(x), start_pos, freqs_cis, mask)
  27. out = h + self.feed_forward(self.ffn_norm(h))
  28. return out

Attention

为了实现Group Query Attention,这里用到了一个函数repeat_kv,它的作用是将key和value的head维度重复n_rep次,以匹配query的head数。repeat_kv函数使用 expand 方法将输入张量在第四个维度上扩展 n_rep 次,并使用 reshape 方法将其调整为适当的形状

  1. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  2. """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
  3. bs, slen, n_kv_heads, head_dim = x.shape
  4. if n_rep == 1:
  5. return x
  6. return (
  7. x[:, :, :, None, :]
  8. .expand(bs, slen, n_kv_heads, n_rep, head_dim)
  9. .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
  10. )
  11. ?# 精简版Attention
  12. class Attention(nn.Module):
  13. def __init__(self, args: ModelArgs):
  14. super().__init__()
  15. self.wq = Linear(...)
  16. self.wk = Linear(...)
  17. self.wv = Linear(...)
  18. self.freqs_cis = precompute_freqs_cis(dim, max_seq_len * 2)
  19. ?
  20. def forward(self, x: torch.Tensor):
  21. bsz, seqlen, _ = x.shape
  22. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
  23. xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
  24. xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  25. xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  26. # attention 操作之前,应用旋转位置编码
  27. xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
  28. #...
  29. # 进行后续Attention计算
  30. scores = torch.matmul(xq, xk.transpose(1, 2)) / math.sqrt(dim)
  31. scores = F.softmax(scores.float(), dim=-1)
  32. output = torch.matmul(scores, xv) # (batch_size, seq_len, dim)

FeedForward类与SwiGLU激活函数

FeedForward类实现的是:

\[\begin{equation} FFN_{swiGLU}(x, W, V, W_2)=(Swish1 (xW) \bigotimes xV)W_2 \end{equation}\]

?
使用的激活函数是SwiGLU,这里有:

\[\begin{equation}SwiGLU=Swish(Wx + b) \bigotimes (Vx + c)\end{equation} \]

\[\begin{equation}Swish(x) = x \times sigmoid(\beta x)\end{equation} \]

  1. class FeedForward(nn.Module):
  2. def __init__(
  3. self,
  4. dim: int,
  5. hidden_dim: int,
  6. multiple_of: int,
  7. ffn_dim_multiplier: Optional[float],
  8. ): # 我们不妨跳过这个函数,太无聊了
  9. ...
  10. def forward(self, x):
  11. # w2 * silu(w1 * x) * w3
  12. return self.w2(F.silu(self.w1(x)) * self.w3(x))

以下内容参考知乎

\(\beta = 1\)\(swish(x)\)就是$silu(x) $

\[\begin{equation}silu(x) = x \times sigmoid(x) = \frac{x}{1+e^{-x}}\end{equation} \]

函数图像如下:

Transformer.forward()

前向传播就是我们熟悉的 Transformer 前向传播了。

  1. @torch.inference_mode()
  2. def forward(self, tokens: torch.Tensor, start_pos: int):
  3. _bsz, seqlen = tokens.shape # 批大小和序列长度
  4. h = self.tok_embeddings(tokens) # 词嵌入层进行嵌入,得到表示输入序列的张量h
  5. self.freqs_cis = self.freqs_cis.to(h.device) # 将频率转换为与输入张量相同的设备
  6. freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen] # 从预计算的频率张量中提取频率
  7. mask = None # 用于在自注意力机制中屏蔽不必要的位置的mask
  8. if seqlen > 1:
  9. mask = torch.full((seqlen, seqlen), float("-inf"), device=tokens.device) # 创建一个形状为(seqlen, seqlen)的张量,填充为负无穷
  10. mask = torch.triu(mask, diagonal=1) # 上三角矩阵
  11. mask = torch.hstack(
  12. [torch.zeros((seqlen, start_pos), device=tokens.device), mask]
  13. ).type_as(h) # 将mask张量与全零张量水平拼接,以适应输入张量h的维度
  14. for layer in self.layers:
  15. h = layer(h, start_pos, freqs_cis, mask) # 逐层进行transformer计算
  16. h = self.norm(h) # 对输出张量进行归一化
  17. output = self.output(h).float() # 输出层进行线性变换
  18. return output

Tokenizer

Tokenizer类主要调用tiktoken库,没啥好讲的。这里的函数大多是前面定义了一大堆东西,但是翻阅具体业务的时候发现其实还是在调库。

  1. class Tokenizer:
  2. """
  3. Tokenizing and encoding/decoding text using the Tiktoken tokenizer.
  4. """
  5. special_tokens: Dict[str, int]
  6. num_reserved_special_tokens = 256
  7. pat_str = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+" # noqa: E501
  8. def __init__(self, model_path: str):
  9. """
  10. Initializes the Tokenizer with a Tiktoken model.
  11. Args:
  12. model_path (str): The path to the Tiktoken model file.
  13. """
  14. assert os.path.isfile(model_path), model_path
  15. mergeable_ranks = load_tiktoken_bpe(model_path)
  16. num_base_tokens = len(mergeable_ranks)
  17. special_tokens = [
  18. "<|begin_of_text|>", "<|end_of_text|>",
  19. "<|start_header_id|>", "<|end_header_id|>", "<|eot_id|>", # end of turn
  20. "<|reserved_special_token_0|>", "<|reserved_special_token_1|>",
  21. "<|reserved_special_token_2|>", "<|reserved_special_token_3|>", "<|reserved_special_token_4|>",
  22. ] + [
  23. f"<|reserved_special_token_{i}|>"
  24. for i in range(5, self.num_reserved_special_tokens - 5)
  25. ]
  26. self.special_tokens = {
  27. token: num_base_tokens + i for i, token in enumerate(special_tokens)
  28. }
  29. self.model = tiktoken.Encoding(
  30. name=Path(model_path).name, pat_str=self.pat_str,
  31. mergeable_ranks=mergeable_ranks, special_tokens=self.special_tokens,
  32. )
  33. self.n_words: int = self.model.n_vocab
  34. # BOS / EOS token IDs
  35. self.bos_id: int = self.special_tokens["<|begin_of_text|>"]
  36. self.eos_id: int = self.special_tokens["<|end_of_text|>"]
  37. self.pad_id: int = -1
  38. self.stop_tokens = {
  39. self.special_tokens["<|end_of_text|>"],
  40. self.special_tokens["<|eot_id|>"],
  41. }
  42. def encode(
  43. self, s: str, *, bos: bool, eos: bool,
  44. allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
  45. disallowed_special: Union[Literal["all"], Collection[str]] = (),
  46. ) -> List[int]:
  47. """
  48. Encodes a string into a list of token IDs.
  49. Args:
  50. s (str): The input string to be encoded.
  51. bos (bool): Whether to prepend the beginning-of-sequence token.
  52. eos (bool): Whether to append the end-of-sequence token.
  53. allowed_tokens ("all"|set[str]): allowed special tokens in string
  54. disallowed_tokens ("all"|set[str]): special tokens that raise an error when in string
  55. Returns:
  56. list[int]: A list of token IDs.
  57. By default, setting disallowed_special=() encodes a string by ignoring
  58. special tokens. Specifically:
  59. - Setting `disallowed_special` to () will cause all text corresponding
  60. to special tokens to be encoded as natural text (insteading of raising
  61. an error).
  62. - Setting `allowed_special` to "all" will treat all text corresponding
  63. to special tokens to be encoded as special tokens.
  64. """
  65. assert type(s) is str
  66. # The tiktoken tokenizer can handle <=400k chars without pyo3_runtime.PanicException.
  67. TIKTOKEN_MAX_ENCODE_CHARS = 400_000
  68. # Here we iterate over subsequences and split if we exceed the limit of max consecutive non-whitespace or whitespace characters.
  69. MAX_NO_WHITESPACES_CHARS = 25_000
  70. substrs = (
  71. substr
  72. for i in range(0, len(s), TIKTOKEN_MAX_ENCODE_CHARS)
  73. for substr in self._split_whitespaces_or_nonwhitespaces(
  74. s[i : i + TIKTOKEN_MAX_ENCODE_CHARS], MAX_NO_WHITESPACES_CHARS
  75. )
  76. )
  77. t: List[int] = []
  78. for substr in substrs:
  79. t.extend(
  80. # 调用在这里
  81. self.model.encode(
  82. substr,
  83. allowed_special=allowed_special,
  84. disallowed_special=disallowed_special,
  85. )
  86. )
  87. if bos:
  88. t.insert(0, self.bos_id)
  89. if eos:
  90. t.append(self.eos_id)
  91. return t
  92. def decode(self, t: Sequence[int]) -> str:
  93. """
  94. Decodes a list of token IDs into a string.
  95. Args:
  96. t (List[int]): The list of token IDs to be decoded.
  97. Returns:
  98. str: The decoded string.
  99. """
  100. # Typecast is safe here. Tiktoken doesn't do anything list-related with the sequence.
  101. return self.model.decode(cast(List[int], t))
  102. @staticmethod
  103. def _split_whitespaces_or_nonwhitespaces(
  104. s: str, max_consecutive_slice_len: int
  105. ) -> Iterator[str]:
  106. """
  107. Splits the string `s` so that each substring contains no more than `max_consecutive_slice_len`
  108. consecutive whitespaces or consecutive non-whitespaces.
  109. """
  110. current_slice_len = 0
  111. current_slice_is_space = s[0].isspace() if len(s) > 0 else False
  112. slice_start = 0
  113. for i in range(len(s)):
  114. is_now_space = s[i].isspace()
  115. if current_slice_is_space ^ is_now_space:
  116. current_slice_len = 1
  117. current_slice_is_space = is_now_space
  118. else:
  119. current_slice_len += 1
  120. if current_slice_len > max_consecutive_slice_len:
  121. yield s[slice_start:i]
  122. slice_start = i
  123. current_slice_len = 1
  124. yield s[slice_start:]

ChatFormat

ChatFormat类借助Tokenizer类,对Tokenizer进行了进一步包装,提供了encode_headerencode_messageencode_dialog_prompt三种encode方式。

  1. class ChatFormat:
  2. def __init__(self, tokenizer: Tokenizer):
  3. self.tokenizer = tokenizer
  4. def encode_header(self, message: Message) -> List[int]:
  5. tokens = []
  6. tokens.append(self.tokenizer.special_tokens["<|start_header_id|>"])
  7. tokens.extend(self.tokenizer.encode(message["role"], bos=False, eos=False))
  8. tokens.append(self.tokenizer.special_tokens["<|end_header_id|>"])
  9. tokens.extend(self.tokenizer.encode("\n\n", bos=False, eos=False))
  10. return tokens
  11. def encode_message(self, message: Message) -> List[int]:
  12. tokens = self.encode_header(message)
  13. tokens.extend(
  14. self.tokenizer.encode(message["content"].strip(), bos=False, eos=False)
  15. )
  16. tokens.append(self.tokenizer.special_tokens["<|eot_id|>"])
  17. return tokens
  18. def encode_dialog_prompt(self, dialog: Dialog) -> List[int]:
  19. tokens = []
  20. tokens.append(self.tokenizer.special_tokens["<|begin_of_text|>"])
  21. for message in dialog:
  22. tokens.extend(self.encode_message(message))
  23. # Add the start of an assistant message for the model to complete.
  24. tokens.extend(self.encode_header({"role": "assistant", "content": ""}))
  25. return tokens

总结

以上就是全部的源码解读。如有疑问请留言。

原文链接:https://www.cnblogs.com/xiangcaoacao/p/18173863

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号