当前位置:   article > 正文

Llama2 代码学习_llama 代码

llama 代码

准备学习llama2模型的代码

  1. class ModelArgs:
  2. dim: int = 4096
  3. n_layers: int = 32
  4. n_heads: int = 32
  5. n_kv_heads: Optional[int] = None
  6. vocab_size: int = -1 # defined later by tokenizer
  7. multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2
  8. ffn_dim_multiplier: Optional[float] = None
  9. norm_eps: float = 1e-5
  10. max_batch_size: int = 32
  11. max_seq_len: int = 2048

此段代码的作用是定义模型中需要用到的各种超参数,维度,层数,头数,kv头数,词典大小,ffn_dim_multiplier是隐藏维度的可选乘法因子,multiple_of是确保隐藏维度是这个值的倍数,norm_eps为标准化时防止0出现在分母上的一个极小参数,,还有批次大小,序列长度大小

  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))
  6. def _norm(self, x):
  7. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
  8. def forward(self, x):
  9. output = self._norm(x.float()).type_as(x)
  10. return output * self.weight

定义RMS正则化标准,eps为防止分母出现0的极小数,使用nn.Parameter创建一个可学习的参数,维度为dim,值全为1。

torch.rsqrt()可以计算torch中逐个元素的平方根的倒数,tensor.mean(-1, keepdim=True)可以对输入张量(本函数中为最后一维)求平均。

  1. def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
  2. freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
  3. t = torch.arange(end, device=freqs.device) # type: ignore
  4. freqs = torch.outer(t, freqs).float() # type: ignore
  5. freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
  6. return freqs_cis

此段代码用于预计算频率,用于实现Rotary Positional Embedding,freqs是一个频率向量,(torch.arange(start,end,step)方法可以指定创建范围内的一维向量),torch.outer计算了一个频率矩阵,torch.polar将频率矩阵转化为复数形式,得到了预计算的频率项freqs_cis

  1. def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
  2. ndim = x.ndim
  3. assert 0 <= 1 < ndim
  4. assert freqs_cis.shape == (x.shape[1], x.shape[-1])
  5. shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
  6. return freqs_cis.view(*shape)

调整freqs_cis张量形状与x进行广播,torch.ndim可以获取torch的维度(是几维向量),遍历x向量的第i个维度和第i个维度的大小,创建一个新形状shape,除了第二维和最后一维其余与x唯独一样,剩下的两维与freqs_cis一样,使用view方法调整freqs_cis的形状

  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_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
  7. xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
  8. freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
  9. xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
  10. xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
  11. return xq_out.type_as(xq), xk_out.type_as(xk)

通过torch.view_as_complex函数将xq,xk变成复数形式,将freqs_cis广播为xq形式,将位置编码以复数相乘的方法加入xq,xk中,最后再返回实数形式

  1. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  2. bs, slen, n_kv_heads, head_dim = x.shape
  3. if n_rep == 1:
  4. return x
  5. return (
  6. x[:, :, :, None, :]
  7. .expand(bs, slen, n_kv_heads, n_rep, head_dim)
  8. .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
  9. )

计算张量时,经常需要对齐张量,本函数在倒数第二维度增加一维,扩张成x*n_rep

  1. class Attention(nn.Module):
  2. def __init__(self, args: ModelArgs):
  3. super().__init__()
  4. #不定义键值头的话就默认是本地注意力头的数量
  5. self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
  6. #定义模型并行大小
  7. model_parallel_size = fs_init.get_model_parallel_world_size()
  8. #本地注意力头(其实是一个显卡上分配的注意力头)
  9. self.n_local_heads = args.n_heads // model_parallel_size
  10. #键值头
  11. self.n_local_kv_heads = self.n_kv_heads // model_parallel_size
  12. #用于上一个函数中的张量对齐的数
  13. self.n_rep = self.n_local_heads // self.n_local_kv_heads
  14. self.head_dim = args.dim // args.n_heads
  15. self.wq = ColumnParallelLinear(
  16. args.dim,
  17. args.n_heads * self.head_dim,
  18. bias=False,
  19. gather_output=False,
  20. init_method=lambda x: x,
  21. )
  22. self.wk = ColumnParallelLinear(
  23. args.dim,
  24. self.n_kv_heads * self.head_dim,
  25. bias=False,
  26. gather_output=False,
  27. init_method=lambda x: x,
  28. )
  29. self.wv = ColumnParallelLinear(
  30. args.dim,
  31. self.n_kv_heads * self.head_dim,
  32. bias=False,
  33. gather_output=False,
  34. init_method=lambda x: x,
  35. )
  36. self.wo = RowParallelLinear(
  37. args.n_heads * self.head_dim,
  38. args.dim,
  39. bias=False,
  40. input_is_parallel=True,
  41. init_method=lambda x: x,
  42. )
  43. self.cache_k = torch.zeros(
  44. (
  45. args.max_batch_size,
  46. args.max_seq_len,
  47. self.n_local_kv_heads,
  48. self.head_dim,
  49. )
  50. ).cuda()
  51. self.cache_v = torch.zeros(
  52. (
  53. args.max_batch_size,
  54. args.max_seq_len,
  55. self.n_local_kv_heads,
  56. self.head_dim,
  57. )
  58. ).cuda()
  59. def forward(
  60. self,
  61. x: torch.Tensor,
  62. start_pos: int,
  63. freqs_cis: torch.Tensor,
  64. mask: Optional[torch.Tensor],
  65. ):
  66. bsz, seqlen, _ = x.shape
  67. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
  68. xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
  69. xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  70. xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  71. xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
  72. self.cache_k = self.cache_k.to(xq)
  73. self.cache_v = self.cache_v.to(xq)
  74. self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk
  75. self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv
  76. keys = self.cache_k[:bsz, : start_pos + seqlen]
  77. values = self.cache_v[:bsz, : start_pos + seqlen]
  78. # repeat k/v heads if n_kv_heads < n_heads
  79. keys = repeat_kv(keys, self.n_rep) # (bs, cache_len + seqlen, n_local_heads, head_dim)
  80. values = repeat_kv(values, self.n_rep) # (bs, cache_len + seqlen, n_local_heads, head_dim)
  81. xq = xq.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
  82. keys = keys.transpose(1, 2) # (bs, n_local_heads, cache_len + seqlen, head_dim)
  83. values = values.transpose(1, 2) # (bs, n_local_heads, cache_len + seqlen, head_dim)
  84. scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
  85. if mask is not None:
  86. scores = scores + mask # (bs, n_local_heads, seqlen, cache_len + seqlen)
  87. scores = F.softmax(scores.float(), dim=-1).type_as(xq)
  88. output = torch.matmul(scores, values) # (bs, n_local_heads, seqlen, head_dim)
  89. output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
  90. return self.wo(output)

Attention类的定义,在init函数中将本地头和键值头根据模型并行数进行划分,定义了四个线形层wq,wk,wv,wo分别用于查询,键,值,输出。

在forward方法中,先获取x的shape,接着通过线性层计算查询,键,值(其实就是把x中的batch_size和seqlen提取出来,将x变为(bsz, seqlen, self.n_local_heads, self.head_dim)的形状),接着将键,值应用于旋转编码,放入缓存,再将k和v从缓存中取出,并对齐(此处主要是消除并行的影响),之后进行k,q,v的计算。

个人理解:这里注意力层整体的输入维度和输出维度即是x的维度(batch_size,seqlen,-1)

  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. super().__init__()
  10. hidden_dim = int(2 * hidden_dim / 3)
  11. # custom dim factor multiplier
  12. if ffn_dim_multiplier is not None:
  13. hidden_dim = int(ffn_dim_multiplier * hidden_dim)
  14. hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  15. self.w1 = ColumnParallelLinear(
  16. dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x
  17. )
  18. self.w2 = RowParallelLinear(
  19. hidden_dim, dim, bias=False, input_is_parallel=True, init_method=lambda x: x
  20. )
  21. self.w3 = ColumnParallelLinear(
  22. dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x
  23. )
  24. def forward(self, x):
  25. return self.w2(F.silu(self.w1(x)) * self.w3(x))

前馈网络层用于对注意力层的输出进行进一步的处理,每个transformer块中都有一个注意力层和前馈层,是一个全连接的神经网络,在每个位置上独立处理输入

  1. class TransformerBlock(nn.Module):
  2. def __init__(self, layer_id: int, args: ModelArgs):
  3. super().__init__()
  4. self.n_heads = args.n_heads
  5. self.dim = args.dim
  6. self.head_dim = args.dim // args.n_heads
  7. self.attention = Attention(args)
  8. self.feed_forward = FeedForward(
  9. dim=args.dim,
  10. hidden_dim=4 * args.dim,
  11. multiple_of=args.multiple_of,
  12. 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. h = x + self.attention.forward(
  25. self.attention_norm(x), start_pos, freqs_cis, mask
  26. )
  27. out = h + self.feed_forward.forward(self.ffn_norm(h))
  28. return out

transformer模块,包含注意力层和前馈层,每个层之前都需要正则化

  1. class Transformer(nn.Module):
  2. def __init__(self, params: ModelArgs):
  3. super().__init__()
  4. self.params = params
  5. self.vocab_size = params.vocab_size
  6. self.n_layers = params.n_layers
  7. self.tok_embeddings = ParallelEmbedding(
  8. params.vocab_size, params.dim, init_method=lambda x: x
  9. )
  10. self.layers = torch.nn.ModuleList()
  11. for layer_id in range(params.n_layers):
  12. self.layers.append(TransformerBlock(layer_id, params))
  13. self.norm = RMSNorm(params.dim, eps=params.norm_eps)
  14. self.output = ColumnParallelLinear(
  15. params.dim, params.vocab_size, bias=False, init_method=lambda x: x
  16. )
  17. self.freqs_cis = precompute_freqs_cis(
  18. # Note that self.params.max_seq_len is multiplied by 2 because the token limit for the Llama 2 generation of models is 4096.
  19. # Adding this multiplier instead of using 4096 directly allows for dynamism of token lengths while training or fine-tuning.
  20. self.params.dim // self.params.n_heads, self.params.max_seq_len * 2
  21. )
  22. @torch.inference_mode()
  23. def forward(self, tokens: torch.Tensor, start_pos: int):
  24. _bsz, seqlen = tokens.shape
  25. h = self.tok_embeddings(tokens)
  26. self.freqs_cis = self.freqs_cis.to(h.device)
  27. freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen]
  28. mask = None
  29. if seqlen > 1:
  30. mask = torch.full(
  31. (seqlen, seqlen), float("-inf"), device=tokens.device
  32. )
  33. mask = torch.triu(mask, diagonal=1)
  34. # When performing key-value caching, we compute the attention scores
  35. # only for the new sequence. Thus, the matrix of scores is of size
  36. # (seqlen, cache_len + seqlen), and the only masked entries are (i, j) for
  37. # j > cache_len + i, since row i corresponds to token cache_len + i.
  38. mask = torch.hstack([
  39. torch.zeros((seqlen, start_pos), device=tokens.device),
  40. mask
  41. ]).type_as(h)
  42. for layer in self.layers:
  43. h = layer(h, start_pos, freqs_cis, mask)
  44. h = self.norm(h)
  45. output = self.output(h).float()
  46. return output

在forward函数中,对输入的 token 索引进行嵌入操作,通过freqs_cis提取频率信息,创建注意力掩码,遍历transformer层,正则化,输出。

将对角线以下的全0矩阵和以上的全mask矩阵进行水平拼接,并与输入数据h的数据类型保持一致

部分参考llama源码学习 | model.py - 知乎 (zhihu.com)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/690747
推荐阅读
相关标签
  

闽ICP备14008679号