Quadratic Attention Bottleneck › Compute Analysis: The Operations
Language AI HandbookAll chapters Quadratic Attention Bottleneck › Compute Analysis: The OperationsOne section · Sections in this chapter4 / 13 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
We have seen that attention requires storing an matrix of weights. But how much computation does it take to produce those weights and use them? Understanding the computational cost helps us predict training times, estimate inference latency, and appreciate why efficient attention variants are so valuable.
The answer turns out to be floating-point operations per attention layer, where is the model dimension. To see where this comes from, let's trace through exactly what happens when attention runs, quantifying each operation precisely.
Building Intuition: What Must Be Computed?
Before diving into the math, consider what attention needs to accomplish for each token in the sequence:
- Compare this token to every other token to determine relevance scores
- Normalize those scores into a probability distribution
- Blend information from all tokens according to those probabilities
For a sequence of tokens, step 1 alone requires comparisons per token, and we have tokens, giving us comparisons. This is the fundamental source of quadratic scaling: the all-pairs comparison cannot be avoided in standard attention. Steps 2 and 3 must process the results of step 1, so they also touch entries.
Now let's quantify each step precisely and see how the costs add up.
Stage 1: Computing Attention Scores
The first operation computes how strongly each query should attend to each key. Mathematically, this is the matrix multiplication , where contains all query vectors (one per token) and contains all key vectors.
When we multiply a matrix of shape by a transposed matrix of shape , we get an output. Each entry in this output matrix is a dot product between one query and one key, requiring multiplications and additions. With such entries, the total operation count for this stage is:
where:
- : the number of query-key pairs (one score per pair)
- : the dimension of each query and key vector (typically for heads)
- : accounts for both multiplications and additions in each dot product (counted as a single fused multiply-add operation on modern hardware)
The appears because every token must be compared against every other token. There is no shortcut here: we do not know which pairs will have high attention until we compute all the scores. This is the irreducible cost of the all-pairs comparison.
Stage 2: Softmax Normalization
Raw dot products can be any real number, positive or negative, and their magnitudes depend on the model's learned parameters. To use them as weights in a weighted average, we need to convert each row of scores into a probability distribution that sums to 1. The softmax function accomplishes this, converting each row of scores into non-negative weights that sum to exactly 1.
For a row of attention scores , softmax computes:
where:
- : the raw dot product score for the -th position in the row
- : the exponential of the scaled score. This keeps all weights are positive
- : the normalizing constant, summing over all positions in the row
- : the scaling factor that prevents dot products from growing too large in magnitude, which would push softmax into regions of near-zero gradient
The scaling is a detail from the original Transformer paper, motivated by the observation that without it, dot products grow in magnitude with , pushing gradients to near zero during training. Scaling by keeps the scores in a range where softmax gradients remain healthy.
For each of the rows in the attention matrix, softmax requires exponentiating scores, summing those exponentials, and dividing each of the exponentials by the sum. This contributes roughly operations per row. With rows:
While still quadratic in , the softmax cost lacks the factor, making it smaller than score computation when is large. For typical transformers where to , softmax contributes less than 10% of the total attention FLOPs. It is not negligible, but it is not the dominant term.
Stage 3: Computing the Output
The final step uses the normalized attention weights to compute a weighted combination of value vectors. Each token's output is a blend of all tokens' values, weighted by attention. In matrix form, this is:
where the left factor is the attention weight matrix and the right factor is the value matrix.
This is another matrix multiplication: the attention weights multiplied by the value matrix produces an output. Each of the output elements requires summing across weighted values:
where:
- : the number of weight-value multiplications (every output position must aggregate from all positions)
- : the dimension of each value vector (typically equal to in standard transformers)
- : multiply-add pairs as before
This matches the cost of score computation exactly when . We have encountered two expensive operations, and they dominate the total cost of attention.

The visualization confirms our analysis: score computation and output computation each consume roughly half the total FLOPs (about 49.8% each), while softmax contributes less than 0.4%. The two matrix multiplications involving the attention matrix dominate entirely. Any optimization that targets the softmax step alone will have negligible impact on the overall compute budget.
The Complete Complexity Formula
Combining all three stages, the total computational cost of self-attention for a single head is:
where:
- : sequence length (number of tokens)
- : dimension of query and key vectors (typically , where is the number of heads)
- : dimension of value vectors (typically equal to )
- : model dimension (the full embedding size before splitting into heads)
- : number of attention heads
The simplification to holds because and are both proportional to . In standard transformers, each head operates on dimensions, and since we sum across all heads, the total work scales with the full model dimension .
Why the Quadratic Term Dominates
The formula reveals an important asymmetry in how the two factors affect complexity:
- Doubling quadruples the computation because appears squared
- Doubling only doubles the computation because appears linearly
This asymmetry determines which factor becomes the bottleneck. For a model with processing tokens, the factor dwarfs the factor by a ratio of over 20,000 to 1. The quadratic term completely dominates, which is why sequence length is the bottleneck rather than model size when processing long documents.
The practical consequence is that scaling up the model (increasing ) is far less damaging to inference speed than scaling up the context (increasing ). A model twice as wide is only twice as slow. A model with twice the context length is four times as slow. This is why researchers are far more willing to increase model dimension than context length when staying within a compute budget.
Putting Numbers to the Formula
Let's make this concrete by computing the actual FLOPs for a GPT-2 style model with across a range of sequence lengths:
def attention_flops(n, d):
"""
Calculate FLOPs for self-attention core operations.
Args:
n: Sequence length
d: Model dimension (used for Q@K^T and attn@V)
Returns:
Total FLOPs (counting multiplications and additions)
"""
# Q @ K^T: (n x d) @ (d x n) = n^2 * d multiplies + n^2 * (d-1) adds
# Simplified to 2 * n^2 * d for multiply-accumulate
score_flops = 2 * n * n * d
# Softmax: exp, sum, divide for each row = ~5 * n^2 operations
softmax_flops = 5 * n * n
# attention @ V: (n x n) @ (n x d) = n^2 * d
output_flops = 2 * n * n * d
return score_flops + softmax_flops + output_flops
d = 768
flops_by_length = [(n, attention_flops(n, d)) for n in sequence_lengths]Attention FLOPs (d=768):
Sequence Length FLOPs GFLOPs
--------------------------------------------------
512 806,617,088 0.81
2,048 12,905,873,408 12.91
8,192 206,493,974,528 206.49
32,768 3,303,903,592,448 3303.90The numbers tell the story of quadratic growth. At 512 tokens, a single attention layer performs about 1.6 billion operations, which modern GPUs handle in microseconds. At 2,048 tokens (4x longer), the count grows to roughly 26 billion operations (16x more, confirming the quadratic relationship). By 32,768 tokens, we are approaching 7 trillion operations per layer.
For a complete transformer, multiply these numbers by the layer count. A 12-layer GPT-2 at 4,096 tokens performs over 1.2 trillion attention operations. During training, backpropagation roughly triples this cost (forward pass, backward for computing gradients, backward for applying updates). The computational demands compound rapidly, and attention becomes the dominant bottleneck for long sequences.
In practice, the FLOPs budget for a long-context model is not simply "how long will this take on a single GPU." It also drives decisions about parallelism strategies, batch sizes, gradient checkpointing, and mixed-precision training. Every engineering decision that reduces the effective cost has compounding effects throughout the training pipeline.