实现带 Importance 筛选的多头矩阵乘法(top_k + top_p)
背景:这是一道大模型方向的作业题,核心是在之前多头 matmul 的基础上,引入 token 重要性概率,通过
top_k、top_p筛选重要 token,只对选中的 token 做多头投影;同时支持传入上游梯度,反向计算输入、权重梯度,并且严格规避 PyTorch Autograd 的 side effect。 踩坑重点:不要把 top_p 自动理解成 nucleus 采样(累积概率),题目文档明确是单点概率阈值,这是绝大多数人卡测试用例的根源。
一、需求原文梳理
我们先把任务规范重新整理一遍,所有实现严格对齐这份定义,不额外脑补:
- 基础:沿用之前的多头矩阵乘法逻辑
- 输入 $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]$
- 重要性概率张量 $P \in \mathbb{R}^{b\times s}$:每个元素代表同序列内该 token 的相对重要概率
- 筛选规则(取交集!)
top_k:每条序列只保留概率最高的 top_k 个 token;None等价于top_k = s(序列全长)top_p:保留概率值大于等于 top_p 的 token(单点阈值,不是nucleus累加概率!)- 最终重要token = 同时满足「属于top_k候选」AND「P >= top_p」
- 输出:把所有选中token压平,输出 $O_3 \in \mathbb{R}^{t\times nh\times e}$,$t$ 是全部batch选中token总数,不做padding
- 梯度分支:
- 可选传入上游梯度
dO3,形状和 $O_3$ 一致 - 传入:计算
grad_input (dA1)、grad_weight (dW1) - 不传入:直接返回两个None,不构建计算图,节省显存
- 可选传入上游梯度
- 约束:不能修改原始输入张量的
requires_grad,防止 side effect,测试用例有该检查
⚠️ 经典踩坑点: 很多人做LLM采样做多了,看到 top_p 直接默认是 nucleus 采样(概率累加截断),和题目文字冲突,直接导致选中token数量、集合和参考真值不一致,测试失败。
二、整体数据流
| |
三、完整可运行代码(带详细注释)
| |
四、关键技术细节解析
4.1 Mask 构建方式:scatter 全局mask
一开始我尝试直接在topk返回的局部索引上做mask筛选,很容易索引错乱。 更稳妥方案:
torch.topk获取topk索引scatter_在原始[b,s]的bool矩阵上标记True- 和
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,可以等价写成:
| |
4.3 Side effect 规避(作业重点考点)
题目Notice明确提醒:测试输入张量本身不需要梯度,不能修改原tensor的.requires_grad。 ❌ 错误写法:input.requires_grad_(True),直接修改外部张量,会被测试判定side effect。 ✅ 正确方案:detach().clone() 新建独立副本,只让副本开启梯度,计算完梯度直接返回副本的grad,原始张量完全不受影响。
4.4 性能优化:dO3=None 不走反向分支
当不需要梯度时,完全跳过 enable_grad、反向计算,不构建计算图,节省显存与计算开销,符合题目要求。
五、踩坑复盘清单(避坑)
- ❌ 坑1:top_p 当成 nucleus 累积概率采样 → 选中token集合错误,shape、数值全部不对
- ❌ 坑2:matmul 直接相乘,没有对齐head维度 → 维度不匹配RuntimeError
- ❌ 坑3:在topk局部数组上mask,没有scatter回原坐标 → 索引错乱,gather拿到错误token
- ❌ 坑4:直接修改输入tensor的requires_grad → 触发side effect,梯度测试失败
- ❌ 坑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 representsbatch_sizeof sequences, and each sequence hasseq_lenelements, where each element is a row-vector with dimensionhidden_size. We denote the input tensor asA1with 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 fromhidden_size-dim toembed_size-dim. We denote the weight tensor asW1with the shape[h, e].
- the input tensor is a 3D tensor with the shape
- The naive
matmulis just to applyO1[i] = A1[i] @ W1for eachi-th sequence in the batch to get output tensor denoted asO1with the shape[b, s, e]. - The multi-head variant of
matmulinvolves splitting thehdimension ofA1andW1intonum_headsshards equally (denoted asnh, provided as an argument) and performingmatmulon each pair ofA1shard andW1shard individually. This transforms the input tensor into a 4D tensor, denoted asA2with the shape[b, s, nh, hd], and accordingly transforms the weight tensor into a 3D tensor denoted asW2with the shape[nh, hd, e]. As a result, the output tensor becomes a 4D tensor as well, denoted asO2with the shape[b, s, nh, e]. - Building on the multi-head version of
matmul, we introduce an importance probability tensor, denoted asP, with the shape[b, s]. Each element inPrepresents the probability of how important the corresponding element inA1is 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 ast), are then gathered into an output tensor, denoted asO3with 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 thantop_pare considered “important”. The default value is1.0.top_k: An integer in the range[1, ..., seq_len]. For each sequence in the batch, only the elements with thetop_khighest probabilities are considered “important”. Iftop_kis not provided (default isNone), it is treated astop_k = seq_len.
- Additionally, if the optional gradient of the output tensor (
grad_output, denoted asdO3with the same shape asO3) is provided, we should also compute the gradients for the input tensor (grad_input, denoted asdA1with the same shape asA1) and the weight tensor (grad_weight, denoted asdW1with the same shape asW1). IfdO3is not given, we returnNonefor bothdA1anddW1.
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 (eithercpuorcuda), with the same data type (float32,float16, orbfloat16), and do NOT require gradients in any test cases. top_pandtop_kare guaranteed to have valid values within their respective ranges in all test cases.hidden_sizeis guaranteed to be divisible bynum_headsin all test cases.- If
grad_outputis not provided, avoid computing gradients to improve efficiency and save memory. - If
grad_outputis 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
matmuloperation in pytorch, including@,torch.matmul,torch.mm,torch.bmm, andtorch.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 !!