Roofline Model

474 字
2 分钟
Roofline Model

Datawhale
Datawhale

大家好,我是芯缘,是 Datawhale 社区发起的 “llm-algo-leetcode 推理优化方向”组队学习活动的助教。

  • 2026年8月运营助教
  • 2026年9月专业助教

基本概念#

Roofline Model 从内存带宽和计算吞吐两个角度,给出一个 kernel 能达到的性能上限。

Roofline Model
Roofline Model

attainable performance≤min⁡(peak compute throughput,memory bandwidth×arithmetic intensity)\text{attainable performance} \le \min(\text{peak compute throughput}, \text{memory bandwidth} \times \text{arithmetic intensity})arithmetic intensity=compute workdata moved\text{arithmetic intensity} = \frac{\text{compute work}}{\text{data moved}}ridge point=peak compute throughputbandwidth\text{ridge point} = \frac{\text{peak compute throughput}}{\text{bandwidth}}

Low Arithmetic Intensity#

Memory-bound

常见 kernel:

  • Elementwise kernel,例如 GELU
  • Reduction kernel,例如 RMSNorm

优化方法(3):

  • 减少 HBM traffic,例如:FlashAttention,优化算法;
  • 通过 tiling 增加数据复用

以 FP16/BF16 为例,每个元素占 2 bytes。

所以当 M = N = 16, B_K = 64 时:

AI=2×16×16×64(16×64+64×16)×2=8 FLOP/byte\text{AI} = \frac{2 \times 16 \times 16 \times 64}{(16 \times 64 + 64 \times 16) \times 2} = 8 \text{ FLOP/byte}

当 M = N = 64, B_K = 64 时:

AI=2×64×64×64(64×64+64×64)×2=32 FLOP/byte\text{AI} = \frac{2 \times 64 \times 64 \times 64}{(64 \times 64 + 64 \times 64) \times 2} = 32 \text{ FLOP/byte}

tile 变大后,数据复用增加,arithmetic intensity 也会提高。

  • fuse operations,例如 将 GEMM 和 elementwise epilogue 融合、将 normalization 融合到相邻 operator 中、计算 attention 时不显式物化完整 score matrix,例如 FlashAttention

High Arithmetic Intensity#

Compute-bound

典型 kernel 是 GEMM。

假设矩阵 A、B 从 HBM 各读取一次,输出 C 写回一次。对于通用的 M x K 乘 K x N 的 FP16 GEMM:

AI≈2MNK(MK+KN+MN)×2=MNKMK+KN+MN\mathrm{AI} \approx \frac{2MNK}{(MK + KN + MN) \times 2} = \frac{MNK}{MK + KN + MN}

其中,分子 2MNK 是矩阵乘法的计算量,2是因为乘+加;分母里的 MK、KN、MN 分别对应读取 A、读取 B、写回 C 的元素个数,乘以 2 是因为 FP16 每个元素占 2 bytes。

如果进一步令 M = N = K,就会退化成:

AI≈2N33×2N2=N3\mathrm{AI} \approx \frac{2N^3}{3 \times 2N^2} = \frac{N}{3}

所以矩阵规模越大,GEMM 的 arithmetic intensity 通常越高。

优化方法(2):

  • 提高 SM occupancy,保持Tensor Core忙碌
  • 通过 overlap 隐藏减少 compute path 上的 idle time

Overlap 的基本思路:

  • 加载 tile k + 1
  • 计算 tile k
  • 写回 tile k - 1

参考资料#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

评论区

Profile Image of the Author
平昊阳
乘长风,破巨浪, 展鸿图于未央!
--
总访问量
--
访客数
公告
欢迎来到我的个人博客!欢迎关注交流吖!
更多相关公告,见
「社交-留言」。
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
站点统计
文章
210
分类
26
标签
288
总字数
2,382,714
运行时长
0 天
最后活动
0 天前

文章目录