← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6516.b · 生成模型:GPT-6

缓存存储先于键值头扩展

理解等级:高级

本章在将键值 repeat_interleave 到查询头数之前保存 next_cache,因此持久缓存保持较少KV头;注意力计算时的显式重复仍可能产生临时内存和带宽成本。比较GQA资源时要区分缓存占用与计算临时张量。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • · 查看原书依据

      next_cache = (keys, values) keys = keys.repeat_interleave( #D self.group_size, dim=1 #D ) #D values = values.repeat_interleave( #D self.group_size, dim=1 #D ) #D attn_scores = queries @ keys.transpose(2, 3) attn_scores = attn_scores.masked_fill(mask, -torch.inf) attn_weights = torch.softmax( attn_scores / self.head_dim**0.5, dim=-1 ) context = (attn_weights @ values).transpose(1, 2) context = context.reshape(b, num_tokens, self.d_out) return self.out_proj(context), next_cache #A The shape is (b, num_tokens, num_heads * head_dim)

    参考来源

    - 位置:《Build a Reasoning Model (From Scratch)》第09章《附录C Qwen3模型源码》(来源项目:a19c7933-4eda-4176-aebd-30fe7e1ad292;源文件:extracted/Build a Reasoning Model (From Scratch)/_epub-src/OEBPS/Text/appendix-c.html) - 结论依据:摘录中关于缓存存储先于键值头扩展的定义、比较或条件支撑卡片;原书表述不严谨的范围已在覆盖记录逐项限定,不把案例结果外推为普遍结论。 - 原始内容:next_cache = (keys, values) keys = keys.repeat_interleave( #D self.group_size, dim=1 #D ) #D values = values.repeat_interleave( #D self.group_size, dim=1 #D ) #D attn_scores = queries @ keys.transpose(2, 3) attn_scores = attn_scores.masked_fill(mask, -torch.inf) attn_weights = torch.softmax( attn_scores / self.head_dim**0.5, dim=-1 ) context = (attn_weights @ values).transpose(1, 2) context = context.reshape(b, num_tokens, self.d_out) return self.out_proj(context), next_cache #A The shape is (b, num_tokens, num_heads * head_dim)