CS6886 Systems for Deep Learning
Noel Manuel (EP22B035)
IIT Madras
[n × d] → [n × d]: one row per token\[ O \;=\; \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + \text{mask}\right) V \]
Q = X·Wq: what this token is looking forK = X·Wk: what this token offersV = X·Wv: what it hands over[h × n × dk], no arithmetic[n × dk] matricesLlama-3-8B shapes, one layer, n = 8,192 tokens, FP16
| tensor | shape | size |
|---|---|---|
| Q, K, V, O (each) | [32 × 8192 × 128] | 67 MB |
| S = QKᵀ, and P = softmax(S) | [32 × 8192 × 8192] | 4.3 GB each |
Dao, Fu, Ermon, Rudra, Ré, “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness”, NeurIPS 2022.
\[ O_i \;=\; \sum_j p_{ij}\, v_j, \qquad p_{ij} = \frac{e^{\,s_{ij} - m_i}}{\ell_i}, \qquad m_i = \max_j s_{ij}, \qquad \ell_i = \sum_j e^{\,s_{ij} - m_i} \]
\(\ell_i\) is the same for every term of the row, so it can be pulled out of the sum:
\[ O_i \;=\; \sum_j \frac{e^{\,s_{ij} - m_i}}{\ell_i}\, v_j \;=\; \frac{1}{\ell_i} \underbrace{\sum_j e^{\,s_{ij} - m_i}\, v_j}_{o_i} \]
Keep running \(m, \ell, o\) on chip, updated per tile; nothing is divided:
\[ m \leftarrow \max(m, \max_{j \in \text{tile}} s_j), \quad \alpha = e^{\,m_{\text{old}} - m}, \quad \ell \leftarrow \alpha\,\ell + \sum_{j\in\text{tile}} e^{\,s_j - m}, \quad o \leftarrow \alpha\, o + \sum_{j\in\text{tile}} e^{\,s_j - m}\, v_j \]
Online normalizer: Milakov & Gimelshein, “Online normalizer calculation for softmax”, 2018.