26 / 28 · Modern Transformer Architectures
Efficient Transformers: FlashAttention and mixture of experts
Compute attention without storing its full matrix, count the parameters that an expert layer actually uses, and separate memory savings from changes to the model.
Self-Attention · Transformer Architecture · Scaling laws and compute-optimal training · Backpropagation
On this page 6
A longer document can exhaust memory before its model runs out of parameters. Increasing the model width creates a different problem: every token must pass through more weights. We need to identify which objects occupy memory and which operations every token actually executes before deciding how to scale.
Stored scores and dense transformations#
Consider one attention head with sequence length and head width . Its query, key and value matrices have shape . The output has the same shape. Scaled dot-product attention is
Both and contain entries. The two matrix multiplications require work proportional to . Doubling the length therefore quadruples the score count, even though , , and only double in size. These are different growth rates within the same operation.
The feed-forward network has another scaling rule. A two-matrix FFN maps width to hidden width and back, independently at each token. Its matrix weights number , and every token uses both matrices. Attention mixes positions; the FFN spends its computation transforming a position’s features. Their definitions and shapes remain unchanged here.
Following the movement of arrays#
A GPU has a large device-memory store and much smaller fast storage close to its arithmetic units. A straightforward implementation writes the complete score array, reads it for softmax, writes probabilities, then reads them for the value mixture. Extra reads and writes can dominate runtime even when the formulas contain relatively little arithmetic between them.
That observation depends on hardware and workload. A large matrix multiplication may be limited by arithmetic throughput, while a small elementwise pass may be limited by memory bandwidth. Counting floating-point operations alone cannot identify the bottleneck. FlashAttention reorganizes these particular operations around the memory hierarchy (Dao et al., 2022, §§2.2–3.2).
FlashAttention#
We can form each output row while keeping only a small piece of its scores. The difficulty is softmax: a new score can change the normalization of every contribution already processed. A running maximum and a rescaled sum make those contributions compatible.
Combining partial softmax sums#
For already processed keys, let be the largest score, the sum of shifted exponentials, and their value-weighted numerator. Here is a vector of width . For a new nonempty block , define
Why rescale the previous terms? Each old exponential satisfies . The same factor therefore converts both the old denominator and numerator to the new reference level. After the final block, . This derives the merge from ordinary softmax; no probabilities are discarded.
Initialize from the first nonempty allowed block. A fully masked block contributes nothing and is skipped. If a whole query row has no allowed key, the normalized distribution is undefined; our construction rejects it. Computing a difference between two negative infinities would not define a meaningful output.
Worked example. Specify five scores as logarithms of masses and five two-coordinate values:
| Key | Mass | Value |
|---|---|---|
| 1 | 3 | |
| 2 | 1 | |
| 3 | 6 | |
| 4 | 2 | |
| 5 | 4 |
These are newly specified mathematical inputs. Process keys 1–2, then key 3, then keys 4–5. The running states are
| Processed keys | |||
|---|---|---|---|
| 1–2 | |||
| 1–3 | |||
| 1–5 |
The output is . Directly weighting the values by their masses and dividing by the total mass 16 gives the same result. If only keys 2–4 are allowed, their masses sum to 9 and the output becomes . Masking changes the allowed distribution before normalization.
Applying the merge to tiles#
For several query rows, retain one state per row. Load a tile of keys and values, compute a small rectangle of scores, apply the allowed-key mask, then merge its contribution. The rectangle can be discarded once those row states have been updated. Causal attention can skip rectangles entirely beyond the diagonal; a rectangle crossing the boundary still needs elementwise masking.
The merge rule does not prescribe the best tile size or thread layout. Those choices depend on how many query, key, value, score and accumulator entries fit in fast memory. Our scalar-loop implementation verifies the algebra and mask behavior. It does not implement a GPU kernel or measure its speed.
Reconstructing intermediates during differentiation#
Backpropagation needs probabilities to propagate derivatives through the value mixture and softmax. Given , and saved row normalization statistics, the same score tiles and probabilities can be reconstructed when needed. This trades additional arithmetic for less persistent storage and less movement of the large intermediate arrays. Dropout, when used, additionally requires reproducible mask information; replaying a different mask would differentiate a different computation.
What equality means in finite precision#
With the same scores, values and mask, tiled and materialized attention represent the same real-arithmetic function. Floating-point sums depend on their order, and intermediate precision can differ between implementations. Bitwise identity is therefore a separate requirement. Our checks compare all six orders of the three blocks, and shifts of every score by or , with a tolerance of . The shift test also exercises the subtraction of the running maximum.
Separating stored bytes from memory traffic#
For an explicit storage inventory, use one head, , two-byte entries in , and four-byte entries for each running and . The reference retains both complete and . The streamed version retains and two row statistics:
These byte counts exclude on-chip tiles, allocator overhead, other layers, gradients and optimizer state. They describe this stated inventory, not peak framework memory or every conventional implementation.
Which arrays remain in memory
The IO analysis counts transfers rather than simultaneous stored bytes. With fast-memory capacity measured in scalar entries, a key/value tile can contain on the order of rows. Visiting all key tiles requires on the order of passes over query/output states of size , giving the term . Dao et al.’s Theorem 2 formalizes this analysis for its two-level memory model with . The practical advantage over materialized attention requires enough fast memory relative to ; it is not a universal speed guarantee. Dense arithmetic still scales as .
Improving the execution schedule#
FlashAttention-2 reduces non-matrix arithmetic, parallelizes query-row blocks and changes how work is divided among warps. Keeping an unnormalized output accumulator until the final division is one such reduction. Its row-oriented work split can also avoid combining partial output vectors between warps. These are execution choices for the same attention function (Dao, 2023, §§3.1–3.3). Our arithmetic example does not establish a speedup for either kernel version.
Mixture of experts#
An expert layer provides several FFNs and routes a token to a subset of them. Attention still determines which positions communicate. The expert choice determines which feature transformation a position receives. Experts are learned parameter sets; their index does not establish a human-readable specialty.
Conditional use of larger parameter sets#
Increasing the width of one dense FFN makes every token use the extra weights. Providing separate FFNs with top- routing lets a token use only experts. Increasing at fixed expert size and increases the available parameter set without proportionally increasing expert matrix multiplication per token. Router work and communication still grow or change, so the entire layer’s cost is not constant.
Specifying the gate convention#
A router maps a token vector to logits. Softmax gives probabilities . Let be the selected top- indices. For our illustrative renormalized gate,
For probabilities , top-2 weights become . If one output coordinate of the selected experts is 3 and −6, the mixture coordinate is 0. A large routing probability does not prevent cancellation between expert outputs.
Switch uses top-1 with the selected probability retained, rather than renormalizing that single weight to one (Fedus, Zoph and Shazeer, 2022, §2.1). For the same first expert, that convention gives . The retained probability supplies a differentiable path to router logits while the selected index is fixed. The discrete choice itself remains nondifferentiable at a routing boundary.
Counting allocated and touched weights#
Use , hidden width , experts and . Include both affine biases in each two-matrix expert and a router bias. A token touches the router and two selected experts.
| Quantity | Calculation | Parameters |
|---|---|---|
| One expert | 123 | |
| Router | 35 | |
| Whole expert layer | 650 | |
| Touched by one token | 281 |
This count excludes attention, normalization, embeddings and all other layers. It is not a FLOP count: a parameter can be used multiple times, routing requires reductions, and batching changes reuse. A model may also use most experts somewhere within a batch, so sparsity per token does not imply sparse optimizer storage for the entire training run.
Balancing assignments and probabilities#
For top-1 routing of tokens, let be the fraction assigned to expert , and its mean router probability before capacity filtering. The Switch auxiliary term is
The assignment fractions are treated as constants for differentiation; the mean probabilities carry gradients (Fedus, Zoph and Shazeer, 2022, §2.2). With assignment counts out of 15 and mean probabilities , the value before multiplying by is . Uniform assignments and probabilities give 1; complete collapse onto one expert gives 5. These are comparison cases, not a claim that 1 is a universal mathematical lower bound over all coupled router configurations.
Capacity and unprocessed assignments#
An implementation may allocate token slots per expert, with capacity factor . Using the same top-1 counts, capacity 3 leaves four assignments unprocessed, although four allocated slots elsewhere are empty. Increasing capacity to 4 reduces unprocessed assignments to two and creates seven empty slots.
Empty slots do not resolve another expert’s overload
| Capacity | Skipped | Empty slots |
|---|---|---|
| 3 | 4 | 4 |
| 4 | 2 | 7 |
| 5 | 1 | 11 |
In the Switch policy, a token whose expert assignment exceeds capacity bypasses that expert computation through the residual path. It is not deleted from the sequence. Other systems can choose a different overflow policy; rerouting, dropping and capacity-free scheduling are different algorithms and must be specified separately.
Storage and communication remain#
All experts need weights somewhere, even when one token uses only a few. Sharding experts across devices exchanges token representations and expert outputs between their owners. Skewed routing can make one device determine the completion time while others wait. A sparse parameter count therefore needs to be accompanied by allocated memory, assignment balance, capacity policy and communication measurements before it becomes a performance argument.
The modern Transformer block#
Several changes address distinct costs and can be combined. Pre-normalization controls the residual path; RMSNorm and rotary positions change specific computations inside it. Neither implies an expert layer or FlashAttention.
SwiGLU uses two input projections whose outputs are multiplied coordinatewise, followed by an output projection. With column-vector inputs and no biases,
Here have shape and has shape , giving weights. A width-4 input with hidden width 6 uses 72 weights, the same as a two-matrix bias-free FFN with hidden width 9. Equal counts do not make their functions identical (Shazeer, 2020, §2).
Grouped-query attention (GQA) shares a key/value head among several query heads (Ainslie et al., 2023, §2.2). With layers, batch size , cached length , key/value heads, head width and bytes per entry, a plain KV cache occupies
For , , , six query heads, and , using six, two or one KV heads gives 108, 36 or 18 KiB. This excludes padding, metadata and other stored tensors. Sharing heads changes the model’s parameterization; it cannot generally preserve an arbitrary multi-head checkpoint’s output. FlashAttention instead changes how the chosen attention function is evaluated. The two savings can coexist.
What changed#
Tiled attention removes full persistent score/probability matrices while retaining every allowed interaction. Expert routing changes which feature transformation a token receives. GQA reduces the number of distinct cached keys and values. Each needs a different correctness comparison: attention outputs, routing behavior or the adapted model’s quality.
Limitations#
Dense attention still has quadratic arithmetic in sequence length. Small workloads may not benefit from a more elaborate schedule. An imbalanced expert layer can waste capacity and communication time. Fewer KV heads constrain the model. None of the synthetic calculations above measures language quality, accelerator utilization or end-to-end latency.
What you should remember#
Keep normalization state when merging attention blocks. Apply masks before normalization. Count all allocated experts separately from the experts visited by one token. State the gate and overflow conventions. Treat hardware timing as an experiment with its own configuration.
Code#
The standard-library construction reproduces the two-coordinate attention outputs, the storage inventory, expert counts, capacity losses and KV-cache table. It checks block reorderings, large common score shifts and an empty allowed set. Its loops verify arithmetic; they are not implementations or benchmarks of GPU attention or distributed routing.
Next#
An affordable backbone still needs to solve a particular task. Transfer learning examines which information a frozen representation exposes and what changes when its parameters are allowed to move.
References#
- Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra and Christopher Ré. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS, 2022. §§2.2–3.2, Theorems 1–2: tiling, normalization, recomputation and the two-level memory model.
- Tri Dao. FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. 2023. §§3.1–3.3: accumulator, sequence parallelism and work partitioning.
- William Fedus, Barret Zoph and Noam Shazeer. Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity. JMLR, 2022. §§2.1–2.2: top-1 gate, capacity and auxiliary loss.
- Noam Shazeer. GLU Variants Improve Transformer. 2020. §2: gated FFN definitions and matrix count.
- Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, Federico Lebrón and Sumit Sanghai. GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. EMNLP, 2023. §2.2: shared key/value heads.