实现带 Importance 筛选的多头矩阵乘法

本文介绍NJU LLM 课程 assignment0的解法。

实现带 Importance 筛选的多头矩阵乘法(top_k + top_p)

背景:这是一道大模型方向的作业题,核心是在之前多头 matmul 的基础上,引入 token 重要性概率,通过 top_k、top_p 筛选重要 token,只对选中的 token 做多头投影;同时支持传入上游梯度,反向计算输入、权重梯度,并且严格规避 PyTorch Autograd 的 side effect。 踩坑重点:不要把 top_p 自动理解成 nucleus 采样(累积概率),题目文档明确是单点概率阈值,这是绝大多数人卡测试用例的根源。

一、需求原文梳理

我们先把任务规范重新整理一遍,所有实现严格对齐这份定义,不额外脑补:

  1. 基础:沿用之前的多头矩阵乘法逻辑
    • 输入 $A_1 \in \mathbb{R}^{b\times s\times h}$,权重 $W_1\in \mathbb{R}^{h\times e}$
    • $h$ 可以被 num_heads(nh) 整除,$hd = h / nh$
    • 分头:$A_1 \rightarrow A_2[b,s,nh,hd],\ W_1\rightarrow W_2[nh,hd,e]$
  2. 重要性概率张量 $P \in \mathbb{R}^{b\times s}$:每个元素代表同序列内该 token 的相对重要概率
  3. 筛选规则(取交集!)
    • top_k:每条序列只保留概率最高的 top_k 个 token;None 等价于 top_k = s(序列全长)
    • top_p:保留概率值大于等于 top_p 的 token(单点阈值,不是nucleus累加概率!)
    • 最终重要token = 同时满足「属于top_k候选」AND「P >= top_p」
  4. 输出:把所有选中token压平,输出 $O_3 \in \mathbb{R}^{t\times nh\times e}$,$t$ 是全部batch选中token总数,不做padding
  5. 梯度分支:
    • 可选传入上游梯度 dO3,形状和 $O_3$ 一致
    • 传入:计算 grad_input (dA1)、grad_weight (dW1)
    • 不传入:直接返回两个None,不构建计算图,节省显存
  6. 约束:不能修改原始输入张量的 requires_grad,防止 side effect,测试用例有该检查

⚠️ 经典踩坑点: 很多人做LLM采样做多了,看到 top_p 直接默认是 nucleus 采样(概率累加截断),和题目文字冲突,直接导致选中token数量、集合和参考真值不一致,测试失败。

二、整体数据流

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Input [b, s, h] + Weight [h, e] + Probs [b, s]
        ↓
构建全局bool mask:mask = (top_k集合) ∩ (probs >= top_p)
        ↓
收集所有满足条件的 (batch_id, seq_pos_id),gather 取出选中token
        ↓
Selected Input [t, h] → reshape 多头 [t, nh, hd]
Weight reshape → [nh, hd, e]
        ↓
Einsum 多头矩阵乘法:"tnh,nhe->tne"
        ↓
Output [t, nh, e]
        ↓
可选:grad_output 上游梯度 → Autograd 反向得到 grad_input / grad_weight

三、完整可运行代码(带详细注释)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import torch


def matmul_with_importance(
        input: torch.Tensor,
        weight: torch.Tensor,
        probs: torch.Tensor,
        num_heads: int,
        top_p: float = 1.0,
        top_k: int | None = None,
        grad_output: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
    """  
    带重要性筛选的多头矩阵乘法,严格遵循作业规范:top_k + 单点top_p取交集  
    Args:        
        input: 原始输入张量 A1, shape [b, s, h]        
        weight: 权重张量 W1, shape [h, e]        
        probs: 每个token的重要性概率P, shape [b, s]  
        num_heads: 头数 nh,要求 h % num_heads == 0        
        top_p: 单点概率阈值 [0,1],保留 prob >= top_p 的token  
        top_k: 每条序列最多保留概率最高的top_k个token;None代表等于序列长度s  
        grad_output: 上游梯度,Output的梯度,shape [t, nh, e];不传则不计算梯度  
    Returns:        
        Output: 筛选后多头投影结果,shape [t, nh, e],t = 所有batch选中token总数  
        grad_input: input的梯度 [b,s,h],grad_output为None时返回None  
        grad_weight: weight的梯度 [h,e],grad_output为None时返回None  
    """
    b, s, h = input.shape
    h_w, e = weight.shape
    # 合法性校验:输入隐藏维度和权重输入维度一致,隐藏维度可以被头数整除  
    assert h == h_w, "hidden size mismatch between input and weight"
    assert h % num_heads == 0, "hidden size must be divisible by num_heads"
    hd = h // num_heads  # 每个头的维度 head_dim  
    # ===================== Step1: 构建筛选mask(top_k ∩ probs >= top_p)=====================    
    if top_k is None:
        top_k = s
    top_k = min(top_k, s)  # 防止传入超过序列长度的top_k  

    # 1. 取出每个序列概率最高top_k个token的索引  
    _, topk_idx = torch.topk(probs, k=top_k, dim=1)  # [b, top_k]  
    # 2. 构建全局bool mask:标记哪些位置属于top_k集合(scatter回原[b,s]空间)  
    mask_topk = torch.zeros_like(probs, dtype=torch.bool)
    mask_topk.scatter_(dim=1, index=topk_idx, value=True)

    # 3. 单点top_p阈值mask:概率大于等于top_p  
    mask_topp = probs >= top_p

    # 4. 最终mask:两个条件取交集,同时满足才是重要token [b, s]  
    mask = torch.logical_and(mask_topk, mask_topp)

    # ===================== Step2: 收集所有有效token坐标,gather取值 =====================    
    # 生成batch坐标矩阵,展开后取出mask为True的位置  
    batch_ids = torch.arange(b, device=probs.device, dtype=torch.long)[:, None].expand(-1, s)[mask]
    # 生成序列位置坐标矩阵,展开后取出mask为True的位置  
    seq_pos_ids = torch.arange(s, device=probs.device, dtype=torch.long)[None, :].expand(b, -1)[mask]

    # 按坐标取出选中的token,得到 [t, h]    
    input_selected = input[batch_ids, seq_pos_ids, :]  
    t = input_selected.shape[0]

    # ===================== Step3: 多头矩阵乘法(Einsum实现,维度对齐安全) =====================    
    # 选中token分头:[t, h] -> [t, nh, hd]  
    A_s2 = input_selected.reshape(-1, num_heads, hd)
    # 权重分头:[h, e] -> [nh, hd, e]  
    W2 = weight.reshape(num_heads, hd, e)
    # einsum签名解释:t=token总数,n=head,h=head_dim,e=输出维度  
    # 对同一个head n,收缩head_dim,输出 [t, n, e]    
    Output = torch.einsum("tnh,nhe->tne", A_s2, W2)

    # ===================== Step4: 梯度分支(grad_output=None直接返回,不构建计算图) =====================    
    if grad_output is None:
        return Output, None, None

        # 梯度计算分支:使用detach+clone新建临时张量,避免修改原始张量requires_grad,规避side effect  
    with torch.enable_grad():
        input_tmp = input.detach().clone().requires_grad_(True)
        weight_tmp = weight.detach().clone().requires_grad_(True)

        # 前向计算在临时副本上复现  
        input_selected_tmp = input_tmp[batch_ids, seq_pos_ids, :]
        A_s2_tmp = input_selected_tmp.reshape(-1, num_heads, hd)
        W2_tmp = weight_tmp.reshape(num_heads, hd, e)
        Output_tmp = torch.einsum("tnh,nhe->tne", A_s2_tmp, W2_tmp)

        # 反向传播,传入上游梯度grad_output  
        Output_tmp.backward(gradient=grad_output)
        grad_input = input_tmp.grad
        grad_weight = weight_tmp.grad

    return Output, grad_input, grad_weight


# ---------------- 本地测试脚本 ----------------
if __name__ == "__main__":
    device = "cuda" if torch.cuda.is_available() else "cpu"
    dtype = torch.float32

    # 测试超参,和case1对齐  
    b = 2
    s = 5
    h = 4
    nh = 2
    hd = h // nh
    e = 3
    top_p = 0.5
    top_k = 3

    torch.manual_seed(42)
    input = torch.randn(b, s, h, device=device, dtype=dtype)
    weight = torch.randn(h, e, device=device, dtype=dtype)
    probs = torch.rand(b, s, device=device, dtype=dtype)

    print("===== 前向测试(无梯度) =====")
    output, grad_in, grad_w = matmul_with_importance(
        input=input,
        weight=weight,
        probs=probs,
        num_heads=nh,
        top_p=top_p,
        top_k=top_k,
        grad_output=None
    )
    print(f"Output shape: {output.shape}")
    print(f"grad_input is None: {grad_in is None}, grad_weight is None: {grad_w is None}\n")

    print("===== 梯度测试(传入grad_output) =====")
    t = output.shape[0]
    grad_output = torch.randn(t, nh, e, device=device, dtype=dtype)
    output2, grad_in2, grad_w2 = matmul_with_importance(
        input=input,
        weight=weight,
        probs=probs,
        num_heads=nh,
        top_p=top_p,
        top_k=top_k,
        grad_output=grad_output
    )
    print(f"Output shape: {output2.shape}")
    print(f"grad_input shape: {grad_in2.shape}, grad_weight shape: {grad_w2.shape}")

四、关键技术细节解析

4.1 Mask 构建方式:scatter 全局mask

一开始我尝试直接在topk返回的局部索引上做mask筛选,很容易索引错乱。 更稳妥方案:

  1. torch.topk 获取topk索引
  2. scatter_ 在原始 [b,s] 的bool矩阵上标记True
  3. 和 probs >= top_p 的mask做逻辑与好处:坐标始终对齐原始序列,不会出现索引映射错误,也是测试用例稳定通过的关键。

4.2 多头矩阵乘法为什么用 einsum?

一开始直接写 torch.matmul(A_s2, W2) 会报错: A_s2 [t, nh, hd],W2 [nh, hd, e],matmul会把t和nh都当成batch维度,要求维度匹配。 einsum("tnh,nhe->tne") 显式声明:同一个head维度n做配对收缩,语义清晰,不容易踩广播坑。 如果你不想用einsum,可以等价写成:

1
Output = torch.matmul(A_s2.unsqueeze(-2), W2.unsqueeze(0)).squeeze(-2)

4.3 Side effect 规避(作业重点考点)

题目Notice明确提醒:测试输入张量本身不需要梯度,不能修改原tensor的.requires_grad。 ❌ 错误写法:input.requires_grad_(True),直接修改外部张量,会被测试判定side effect。 ✅ 正确方案:detach().clone() 新建独立副本,只让副本开启梯度,计算完梯度直接返回副本的grad,原始张量完全不受影响。

4.4 性能优化:dO3=None 不走反向分支

当不需要梯度时,完全跳过 enable_grad、反向计算,不构建计算图,节省显存与计算开销,符合题目要求。

五、踩坑复盘清单(避坑)

  1. ❌ 坑1:top_p 当成 nucleus 累积概率采样 → 选中token集合错误,shape、数值全部不对
  2. ❌ 坑2:matmul 直接相乘,没有对齐head维度 → 维度不匹配RuntimeError
  3. ❌ 坑3:在topk局部数组上mask,没有scatter回原坐标 → 索引错乱,gather拿到错误token
  4. ❌ 坑4:直接修改输入tensor的requires_grad → 触发side effect,梯度测试失败
  5. ❌ 坑5:参数名和测试文件不匹配(A1/W1/P vs input/weight/probs)→ 关键字传参报错

六、拓展思考

这个结构可以直接迁移到稀疏注意力、检索增强、LLM动态token路由场景:只对高重要性token做投影/注意力计算,降低计算量。 和常规的top-p采样的区别:常规生成采样是概率归一后的词汇表分布,而本题是独立定义的token重要性分数,语义完全分开,这也是为什么题目特意强调“the probability of how important the corresponding element in A1 is relative to other elements within the same sequence”。

附录 作业要求

Task 1: MatMul with Importance (100 points)

TODO

You are required to implement a python function named matmul_with_importance in src/functional.py with pytorch.

Explanation

  • According to its docstring, this function is to apply a special variant of matrix multiplication operation (denoted as matmul) of two tensors, where:
    • the input tensor is a 3D tensor with the shape [batch_size, seq_len, hidden_size], which represents batch_size of sequences, and each sequence has seq_len elements, where each element is a row-vector with dimension hidden_size. We denote the input tensor as A1 with the shape [b, s, h].
    • the weight tensor is a 2D tensor with the shape [hidden_size, embed_size], which represents a projection matrix that projects any row vector from hidden_size-dim to embed_size-dim. We denote the weight tensor as W1 with the shape [h, e].
  • The naive matmul is just to apply O1[i] = A1[i] @ W1 for each i-th sequence in the batch to get output tensor denoted as O1 with the shape [b, s, e].
  • The multi-head variant of matmul involves splitting the h dimension of A1 and W1 into num_heads shards equally (denoted as nh, provided as an argument) and performing matmul on each pair of A1 shard and W1 shard individually. This transforms the input tensor into a 4D tensor, denoted as A2 with the shape [b, s, nh, hd], and accordingly transforms the weight tensor into a 3D tensor denoted as W2 with the shape [nh, hd, e]. As a result, the output tensor becomes a 4D tensor as well, denoted as O2 with the shape [b, s, nh, e].
  • Building on the multi-head version of matmul, we introduce an importance probability tensor, denoted as P, with the shape [b, s]. Each element in P represents the probability of how important the corresponding element in A1 is relative to other elements within the same sequence.
  • As a result, we aim to apply matmul only to the “important” elements in each sequence. The projected vectors of these important elements, totaling total_important_seq_len (denoted as t), are then gathered into an output tensor, denoted as O3 with the shape [t, nh, e].
  • To precisely define what is considered “important”, we provide two optional arguments:
    • top_p: A float in the range [0., 1.]. Only elements with a probability equal to or higher than top_p are considered “important”. The default value is 1.0.
    • top_k: An integer in the range [1, ..., seq_len]. For each sequence in the batch, only the elements with the top_k highest probabilities are considered “important”. If top_k is not provided (default is None), it is treated as top_k = seq_len.
  • Additionally, if the optional gradient of the output tensor (grad_output, denoted as dO3 with the same shape as O3) is provided, we should also compute the gradients for the input tensor (grad_input, denoted as dA1 with the same shape as A1) and the weight tensor (grad_weight, denoted as dW1 with the same shape as W1). If dO3 is not given, we return None for both dA1 and dW1.

Summary

In summary, the core of the matmul_with_importance function is to compute and return a tuple of three (optional) tensors: either (O3, dA1, dW1) or (O3, None, None), given as input two tensors A1 and W1 as matmul operators, an importance probability tensor P with top_p and top_k to control “importance”, an optional gradient tensor dO3, and an integer num_heads to split the hidden_size.

Notice

  • All given tensors are randomly initialized from the standard normal distribution N(0, 1) on the same device (either cpu or cuda), with the same data type (float32, float16, or bfloat16), and do NOT require gradients in any test cases.
  • top_p and top_k are guaranteed to have valid values within their respective ranges in all test cases.
  • hidden_size is guaranteed to be divisible by num_heads in all test cases.
  • If grad_output is not provided, avoid computing gradients to improve efficiency and save memory.
  • If grad_output is provided, you can compute gradients using pytorch’s autograd mechanism, but be cautious of potential side effects, which may be checked in the test cases.
  • There are so many ways to perform the matmul operation in pytorch, including @, torch.matmul, torch.mm, torch.bmm, and torch.einsum, among others. It is recommended that you experiment with different methods to implement the task and explore the differences between them.

References

Hints: Here’re some references which may be helpful to your task, or just deepen / broaden your knowledge to pytorch:

!! Remember: it is a fundemental and essential capability to search, read, think and learn from the official English documentation for your answer, try NOT to rely too much on some biased and superficial blogs, e.g. CSDN !!

comments powered by Disqus
使用 Hugo 构建
主题 Stack 由 Jimmy 设计