Minimind 代码解析

2025-07-25

minimind 是一个著名的开源项目。它没有使用各种高度抽象的接口,为我们展示了训练一个语言模型的细节(没有让细节被隐藏在各种第三方库之下)。因此,它也是入门 LLM 的一个很好的开源项目。 这篇文章解析了部分 minimind 的代码,并给出了一些运行结果,帮助对 Pytorch 不熟悉的人快速上手 minimind。

model/minimind.py

Rope

def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
    def rotate_half(x):
        return torch.cat((-x[..., x.shape[-1] // 2:], x[..., : x.shape[-1] // 2]), dim=-1)

    q_embed = (q * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(q) * sin.unsqueeze(unsqueeze_dim))
    k_embed = (k * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(k) * sin.unsqueeze(unsqueeze_dim))
    return q_embed, k_embed

上面是一个用来进行旋转位置编码的函数。

  • 旋转位置编码: 对 $\textbf{x}=(x_0, x_1, \dots, x_{d - 1})$ 进行旋转位置编码按如下公式:
    \(R^d_{\theta,m} \mathbf{x} = \begin{pmatrix} x_0 \\ x_1 \\ x_2 \\ x_3 \\ \vdots \\ x_{d-2} \\ x_{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} -x_1 \\ x_0 \\ -x_3 \\ x_2 \\ \vdots \\ -x_{d-1} \\ x_{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}\)
    在代码中,函数 apply_rotary_pos_emb 的输入为 q, k, cos, sin等。q、k 分别代表注意力机制中的 querykey;cos、sin 分别代表公式中的余弦、正弦向量(观察上面的公式)。 想要具体深入了解 旋转位置编码 的话,可以查看下面这个链接:旋转位置编码

    Attention

    class Attention(nn.Module):
      def __init__(self, args: MiniMindConfig):
          super().__init__()
          self.num_key_value_heads = args.num_attention_heads if args.num_key_value_heads is None else args.num_key_value_heads
          assert args.num_attention_heads % self.num_key_value_heads == 0
          self.n_local_heads = args.num_attention_heads
          self.n_local_kv_heads = self.num_key_value_heads
          self.n_rep = self.n_local_heads // self.n_local_kv_heads
          self.head_dim = args.hidden_size // args.num_attention_heads
          self.q_proj = nn.Linear(args.hidden_size, args.num_attention_heads * self.head_dim, bias=False)
          self.k_proj = nn.Linear(args.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
          self.v_proj = nn.Linear(args.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
          self.o_proj = nn.Linear(args.num_attention_heads * self.head_dim, args.hidden_size, bias=False)
          self.attn_dropout = nn.Dropout(args.dropout)
          self.resid_dropout = nn.Dropout(args.dropout)
          self.dropout = args.dropout
          self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
          # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
    

    注意力层的定义如上,{q、k、v、o}_proj 是线性投影层,{attn_dropout、resid_dropout} 是 dropout 的概率。self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn 这行代码用于检查是否要启用 flash_attn(flash_attn 是一种加速 注意力机制 的方法,详情可以参考flash attention)。

      def forward(self,
                  x: torch.Tensor,
                  position_embeddings: Tuple[torch.Tensor, torch.Tensor],  # 修改为接收cos和sin
                  past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
                  use_cache=False,
                  attention_mask: Optional[torch.Tensor] = None):
          bsz, seq_len, _ = x.shape
          xq, xk, xv = self.q_proj(x), self.k_proj(x), self.v_proj(x)
          xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
          xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
          xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
    
          cos, sin = position_embeddings
          xq, xk = apply_rotary_pos_emb(xq, xk, cos[:seq_len], sin[:seq_len])
    
          # kv_cache实现
          if past_key_value is not None:
              xk = torch.cat([past_key_value[0], xk], dim=1)
              xv = torch.cat([past_key_value[1], xv], dim=1)
          past_kv = (xk, xv) if use_cache else None
    
          xq, xk, xv = (
              xq.transpose(1, 2),
              repeat_kv(xk, self.n_rep).transpose(1, 2),
              repeat_kv(xv, self.n_rep).transpose(1, 2)
          )
    
          if self.flash and seq_len != 1:
              dropout_p = self.dropout if self.training else 0.0
              attn_mask = None
              if attention_mask is not None:
                  attn_mask = attention_mask.view(bsz, 1, 1, -1).expand(bsz, self.n_local_heads, seq_len, -1)
                  attn_mask = attn_mask.bool() if attention_mask is not None else None
    
              output = F.scaled_dot_product_attention(xq, xk, xv, attn_mask=attn_mask, dropout_p=dropout_p, is_causal=True)
          else:
              scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
              scores = scores + torch.triu(
                  torch.full((seq_len, seq_len), float("-inf"), device=scores.device),
                  diagonal=1
              ).unsqueeze(0).unsqueeze(0)  # scores+mask
    
              if attention_mask is not None:
                  extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
                  extended_attention_mask = (1.0 - extended_attention_mask) * -1e9
                  scores = scores + extended_attention_mask
    
              scores = F.softmax(scores.float(), dim=-1).type_as(xq)
              scores = self.attn_dropout(scores)
              output = scores @ xv
    
          output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
          output = self.resid_dropout(self.o_proj(output))
          return output, past_kv
    

    以上是 Attention 的 forawrd 方法。 其中值得注意的是这段代码

          if past_key_value is not None:
              xk = torch.cat([past_key_value[0], xk], dim=1)
              xv = torch.cat([past_key_value[1], xv], dim=1)
          past_kv = (xk, xv) if use_cache else None
    

    它实现了 KV Cache,从而减少了计算量、提升了速度。

  • 为什么要对 KV 进行缓存,而不对 Q 进行缓存? 这涉及到LLM在推理过程中的一个重要特点——自回归。具体内容可以参考为什么要对 KV 进行缓存,而不对 Q 进行缓存?
          bsz, seq_len, _ = x.shape
          xq, xk, xv = self.q_proj(x), self.k_proj(x), self.v_proj(x)
          xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
          xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
          xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
    

    由这段代码可以看出输入张量 x 的形状为 (batch size, seq len, dim)。经过线性投影后得到 xq、xk、xv,形状变为 (batch size, seq len, hidden dim),通过 view 方法,我们将 xq、xk、xv 看成形状为 (batch size, seq len, num heads, head dim),从而便于执行多头注意力机制。

          cos, sin = position_embeddings
          xq, xk = apply_rotary_pos_emb(xq, xk, cos[:seq_len], sin[:seq_len])
    

    这两行为 xq、xk 添加位置编码,使得注意力机制可以识别序列的位置信号。

          xq, xk, xv = (
              xq.transpose(1, 2),
              repeat_kv(xk, self.n_rep).transpose(1, 2),
              repeat_kv(xv, self.n_rep).transpose(1, 2)
          )
    ######################################################
    # 下面便是 repeat_kv 的定义
    def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
      """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
      bs, slen, num_key_value_heads, head_dim = x.shape
      if n_rep == 1:
          return x
      return (
          x[:, :, :, None, :]
          .expand(bs, slen, num_key_value_heads, n_rep, head_dim)
          .reshape(bs, slen, num_key_value_heads * n_rep, head_dim)
      )
    

    将 xq、xk、xv 的形状分别转换为 (batch size, num heads, seq len, head dim)、(batch size, num heads * num repeat, seq len, head dim)、(batch size, num heads * num repeat, seq len, head dim) 这个操作等价于 torch.repeat_interleave(x, dim=2, repeats=n_rep).transpose(1, 2)

也许你会有这样一个疑问,为什么 xk、xv 需要进行一个repeat? 实际上,minimind 实现的不是传统的多头注意力,而是 GQA
GQA 令多个 Query 头共享同一个 Key-Value 头。Query 头的数量比 Key-Value 头的数量更多,下面这张表举了一个示例:

  原始维度 拆分成多头后维度 执行repeat后
xq (batch size, seq len, q dim) (batch size, q head, seq len, q dim / q head) xq不执行 repeat
xk (batch size, seq len, kv dim) (batch size, kv head, seq len, kv dim / kv head) (batch size, kv head * num repeat(= q head), seq len, kv dim / kv head)
xv (batch size, seq len, kv dim) (batch size, kv head, seq len, kv dim / kv head) (batch size, q head, seq len, kv dim / kv head)

其中 (kv dim / kv head) 与 (q dim / q head) 大小相同,kv dim 小于 q dim。执行 GQA 的优势在于 kv dim 小于 q dim,所以 KV Cache 缓存的数据相比于传统的多头注意力更小,从而提升了上下文长度,降低了成本。

MoEGate

class MoEGate(nn.Module):
    def __init__(self, config: MiniMindConfig):
        super().__init__()
        self.config = config
        self.top_k = config.num_experts_per_tok
        self.n_routed_experts = config.n_routed_experts

        self.scoring_func = config.scoring_func
        self.alpha = config.aux_loss_alpha
        self.seq_aux = config.seq_aux

        self.norm_topk_prob = config.norm_topk_prob
        self.gating_dim = config.hidden_size
        self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
        self.reset_parameters()

上面的代码是 MoEGate 的定义,混合专家模型会把数据分配给不同的专家进行处理,从而达到类似术业有专攻的效果。MoEGate 是门选择网络,用来决定如何选择专家。

def forward(self, hidden_states):
        bsz, seq_len, h = hidden_states.shape
        hidden_states = hidden_states.view(-1, h)
        logits = F.linear(hidden_states, self.weight, None)
        if self.scoring_func == 'softmax':
            scores = logits.softmax(dim=-1)
        else:
            raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')

        topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)

        if self.top_k > 1 and self.norm_topk_prob:
            denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
            topk_weight = topk_weight / denominator

        if self.training and self.alpha > 0.0:
            scores_for_aux = scores
            aux_topk = self.top_k
            topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
            if self.seq_aux:
                scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
                ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
                ce.scatter_add_(1, topk_idx_for_aux_loss,
                                torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
                    seq_len * aux_topk / self.n_routed_experts)
                aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
            else:
                mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
                ce = mask_ce.float().mean(0)
                Pi = scores_for_aux.mean(0)
                fi = ce * self.n_routed_experts
                aux_loss = (Pi * fi).sum() * self.alpha
        else:
            aux_loss = 0
        return topk_idx, topk_weight, aux_loss

上面的是 MoEGate 代码