Why Attention Scales
I explore the transformer's attention mechanism, focusing on why scaled dot-product attention and its variants are so effective at scaling.
The original transformer descended from the RNN encoder–decoder (Bahdanau et al., 2014; Cho et al., 2014; Cho et al., 2014). The main contribution of the transformer paper, Attention Is All You Need (Vaswani et al., 2017), was to model relationships between tokens using multi-headed attention rather than recurrent units. The argument was that attention should work better not because it was obviously a better inductive bias, but only that it should scale. While I’ve discussed the transformer before in my history of large language models, I did not work through attention in technical detail. So the only question I want to answer in this post is: how does the scaled dot-product attention in the original transformer work and, in particular, why is it so efficient?
For conciseness, I will assume the reader has some familiarity with the basics, such as tokenization, embeddings, and automatic differentiation. See here for a small but complete implementation.
Soft lookup
I want to start by building up to the attention mechanism from first principles. This will require coming at the problem a little sideways at first, but I think it pays off. And the line of reasoning here follows the intellectual history as well, as the origins of the attention mechanism can be traced to information retrieval literature. This explains the somewhat odd terminology of “queries”, “keys”, and “values”.
Let’s begin. A lookup table maps a query to a value by finding the matching key. This is such a common operation that it’s encoded as a built-in Python data structure, the dict:
keys = list("abcdefghijklmnopqrstuvwxyz")
values = list(range(1, 1 + len(keys)))
lookup = {k: v for k, v in zip(keys, values)}
# Returns 26
query = "z"
lookup[query]
But obviously you can build this yourself. It’s a common computer science homework problem to write your own hash table in C or C++, for example. So here is the same result more verbosely:
def hard_lookup(query, keys, values):
"""
Return value from (key, value) pair where key exactly matches query.
"""
for k, v in zip(keys, values):
if k == query:
return v
raise KeyError(query)
# Returns 26
hard_lookup("z", keys, values)
Using hashing to do this efficiently without the for loop is the main idea behind a hash table. We might call this a hard lookup because it only returns the value associated with the key if there is an exact match. Otherwise, it will raise an error. But now consider this variant of a lookup table that we might call a soft lookup. It returns a weighted average of all the values, where the weights are based on the relevance of each key to the query:
def compute_relevance(q, k):
return int(q == k)
def soft_lookup(query, keys, values):
"""
Return relevance-weighted average of values based on the query.
"""
# Compute relevance-based weights
weights = [compute_relevance(query, k) for k in keys]
# Compute weight normalizer, so that sum_i w_i = 1
wsum = sum(weights)
# Compute output as relevance-weighted average of values
return sum((w / wsum) * v for w, v in zip(weights, values))
# Returns 26.0
soft_lookup("z", keys, values)
Here, I’ve defined “relevance” to be on an exact match and otherwise, so this still returns (now a float), but obviously soft_lookup is more general than hard_lookup since we can use any definition of “relevance” that we want.
Okay, now let’s get more interesting. Imagine that our query, keys, and values are all vectors, here implemented as NumPy arrays:
import numpy as np
def compute_relevance(q, k):
return q @ k.T
def normalize_rows(w):
return np.exp(w) / np.sum(np.exp(w))
def soft_lookup_vec(query, keys, values):
"""
Return relevance-weighted average of values based on the query.
"""
# Compute relevance-based weights between query and every row in keys
weights = [compute_relevance(query, k) for k in keys]
# Normalize weights, so that sum_i w_i = 1
weights = normalize_rows(weights)
# Compute output as relevance-weighted average of values
return weights @ values
query = np.array([1, 2, 3])
keys = np.array([[1, 2, 3], [-3, 0, 1]])
values = np.array([[2, 6], [9, 4]])
# Returns array([2., 6.])
soft_lookup_vec(query, keys, values)
This vector-based version of a soft-lookup uses the dot product to define the relevance of each key with the input query and then it returns a relevance-weighted average of the values associated with each key. Since the query’s score with () dwarfs its score with (), this example amounts to a near-hard-lookup of the value associated with the key , which is .
So why the dot product? Two reasons. First, obviously the dot product is a natural measure of similarity between vectors. Second, the dot product can implement this weighting very efficiently. I’ve intentionally written the above to be more general, but if we hard-code compute_relevance to be the dot product, then the list comprehension reduces to a matrix multiplication, or weights = query @ keys.T.
Context-aware tokens
Now let’s look at attention. In the original transformer paper, the authors propose scaled dot-product attention, defined as:
Without context, this might look confusing. But this is essentially just a fully-vectorized soft lookup function. We can rewrite the previous soft lookup function more compactly as:
softmax = normalize_rows
def attention(query, keys, values):
"""
Return relevance-weighted average of values based on the query.
"""
weights = softmax(query @ keys.T)
return weights @ values
The only difference here is the scale factor . This scale just accounts for the fact that the dot product scores grow with the dimension of the queries and keys. For example, while . More precisely, if the components of a query and key are independent with zero mean and unit variance, their dot product has variance , so dividing by keeps the scores at unit variance. This prevents large scores from saturating the softmax and thus converting the soft lookup into a hard lookup.
The real difference between a soft lookup and attention is that attention automatically learns queries, keys, and values from data. Let’s see this via a small example. Consider the full sentence
Now imagine that we tokenized this sentence and embedded each token into a -dimensional vector, or token embedding. If our sequence has length (here ), then our token embeddings would be an matrix. Let’s call this . We would then compute the queries, keys, and values—each an matrix—by applying linear transformations to :
After we have the scores, what can we do with them? Well, we pay attention to the values, which are also learned, in this case from the same sequence:
The main point is that the queries and keys are learned, where “learning” means that gradient descent on some objective fiddles with the model parameters until the model is “paying attention” to the right pieces of information in order to do well on some task (Figure ).
How can we interpret ? This is again an matrix, and each row is a relevance-weighted combination of the sequence’s tokens (Figure ). Hopefully this connection to our original soft lookup is clear. The point I want to emphasize here is that the output tokens can be thought of as a context-aware sequence of tokens, where the context is defined by the relevance of queries to keys and where “relevance” itself is learned.
Note that here I am describing self-attention, which is attention in which the attention scores and the values both come from the same embeddings . In other words, the model learns relevance-based weights by comparing the sequence to itself, and then it uses those weights to attend to the very same sentence. We’ll discuss cross-attention later.
Also note that I am describing non-causal attention. In Figure , for example, the second “the” can pay attention to “ocean”, even though “ocean” comes after it in the sequence. We’ll discuss causal masking later.
Implementation
Now let’s look at a complete implementation of attention using JAX, Flax, and Optax. First, here is the attention function. At this point, this does not need much explanation. The only thing I want to emphasize is that this is written so that we can perform attention across the leading dimensions (batches and eventually attention heads). Here, is what I have been calling . In practice, the queries, keys, and values can have different dimensions, but throughout this post, I will always assume they are the same.
from flax import nnx
from jax import numpy as jnp
def attention(queries, keys, values):
"""
Scaled dot-product attention over leading dimensions.
"""
d_k = queries.shape[-1]
# Compute scaled scores, QK^T / sqrt(d_k)
scores = jnp.einsum("...sd,...td->...st", queries, keys) / jnp.sqrt(d_k)
# Compute attention weights, softmax(QK^T / sqrt(d_k)).
weights = nnx.softmax(scores)
# Apply values softmax(QK^T / sqrt(d_k))*V
out = jnp.einsum("...st,...td->...sd", weights, values)
return out, weights
Using this function, we can implement a simple attention module, which again needs very little explanation on its own. And then we need a wrapper module that first embeds our tokens—that is, converts them from IDs in a vocabulary to -vectors—before applying attention.
from flax import nnx
class Attention(nnx.Module):
def __init__(self, model_dim, rngs):
self.w_q = nnx.Linear(model_dim, model_dim, rngs=rngs)
self.w_k = nnx.Linear(model_dim, model_dim, rngs=rngs)
self.w_v = nnx.Linear(model_dim, model_dim, rngs=rngs)
def __call__(self, x):
"""
Forward pass of single-headed self-attention.
"""
q = self.w_q(x)
k = self.w_k(x)
v = self.w_v(x)
z, w = attention(q, k, v)
return z, w
class Model(nnx.Module):
def __init__(self, vocab_size, model_dim, rngs):
self.embed = nnx.Embed(vocab_size, model_dim, rngs=rngs)
self.attn = Attention(model_dim, rngs)
self.proj_out = nnx.Linear(model_dim, vocab_size, rngs=rngs)
def __call__(self, x):
"""
Forward pass through embedding and attention and back out.
"""
h = self.embed(x)
z, w = self.attn(h)
logits = self.proj_out(z)
return logits, w
Finally, we can use Optax to train these modules end-to-end using gradient descent and a learning rate of 3e-4. What’s the objective function? It depends on the task. In sequence-to-sequence modeling like neural machine translation—this was the task in the original transformer paper—the objective is to minimize the cross-entropy loss on the target sequence after encoding, attending to, and then decoding a batch. For example, the input sequence might be a German sentence, and the output sequence is the English translation. But in GPT-style training, often called next-token prediction, the model is only a decoder and is trained to predict the next word at each step.
At this moment, I think it’s worth pausing. There is a lot of conceptual machinery here: gradient descent, automatic differentiation, Python libraries like Jax, tokenization algorithms, the embedding layer, the dot product, the attention mechanism, and so forth. I haven’t gone into critical details like positional encoding or multi-headed attention. But I think it’s worth appreciating that at one level of abstraction, this is such a simple, beautiful, and elegant idea. We started with an odd-looking implementation of a key-value lookup and ultimately derived the core mechanism that is a foundational idea behind large language models.
Permutation equivariance
Now let’s look at training the attention mechanism end-to-end, and start to build some intuition for what these scores actually are. Consider a simple task: for each number in a sequence, let’s predict the next highest number that’s also in the sequence. For example:
This is a good problem because it requires that the model pay attention to the numbers, but order does not matter. It does not matter where in the set the next-larger number is. In this problem, the input is a sequence of random one-digit numbers, while the target sequence is the output of the successor function above. Here is some illustrative pseudo-code for training the model. So the input sequence is the src, while the successor sequence is the tgt.
@nnx.jit
def step(model, optimizer, batch):
def loss_fn(model):
logits, _ = model(batch["src"])
loss = optax.softmax_cross_entropy_with_integer_labels(logits, batch["tgt"])
return loss.mean()
loss, grads = nnx.value_and_grad(loss_fn)(model)
optimizer.update(model, grads)
return loss
for i, batch in enumerate(get_batches()):
loss = step(model, optimizer, batch)
print(f"step={i:3d} loss={loss:.4f}")
After training the model, I have visualized the matrix of attention weights or scores for a particular sequence (Figure , top row). The way to read this is as follows. Each row is the weights for the token which labels the row. This is what the model thinks should be attended to for that token. So in row 4, the highest score is for 6, which is the correct successor. In row 6, the highest score is for 7. In row 2, however, the highest weight is actually 4 and then 3. However, the model is still accurate. It is trained to predict the successor, not construct interpretable scores.
Now notice something fundamental to attention. As we have implemented it, attention is on sets of queries, keys, and values. This means that the ordering does not matter. If we were to reorder the tokens in a sequence, we would get an output but with the same reordering (Figure , bottom row). This property is called permutation equivariance. As it stands, this implies that our simple model of attention cannot actually learn relationships that require ordering.
Positional encodings
The successor task only depends on which digits are present. So is the successor to , and the attention mechanism can detect the presence of . Now let’s consider another simple task: each token should predict the token to the right of it, wrapping around so that the last token predicts the first:
In code, this is just tgt = np.roll(src, -1), and we use the same training loop as above. So the neighbor task depends on where each digit sits. So follows because it’s next in the position. Attention, as we have defined it so far, cannot solve this problem (Figure , left). If we train our attention module on this task, we can see that scores are effectively uniformly random, placing roughly weight on each digit.
How can we solve this problem? The idea is dead simple, but in my mind it is important and useful to properly motivate it: we simply add embeddings to our input that define the ordering, called positional encodings.
Positional encodings are vectors added to each token embedding that contains purely positional information. These encodings can be fixed, as in the original transformer, or learned via an embedding layer. In either case, each position gets a different vector, which breaks the permutation symmetry. In this way, positional encodings enforce location information onto the otherwise set-based attention mechanism.
In the original transformer, the authors propose fixed cosine- and sine-waved base encodings:
That said, for didactic purposes, these are overkill. We can solve the neighbor task above with very simple positional encodings, simply embedding a range of numbers. See self.pe below:
class Model(nnx.Module):
def __init__(self, vocab_size, seq_len, model_dim, rngs):
self.embed = nnx.Embed(vocab_size, model_dim, rngs=rngs)
self.attn = Attention(model_dim, rngs)
self.proj_out = nnx.Linear(model_dim, vocab_size, rngs=rngs)
# New learned positional encodings
self.pe = nnx.Embed(seq_len, model_dim, rngs=rngs)
def __call__(self, x):
"""
Forward pass through embedding, attention, and projecting out.
"""
h = self.embed(x) + self.pe(jnp.arange(x.shape[-1]))
z, w = self.attn(h)
logits = self.proj_out(z)
return logits, w
Intuitively, the attention mechanism can only construct a context-aware token based on what is available in the queries and keys. Without positional information, the only possible lookup is by “content”. Operations like “find the ” are possible, but not “find the first ”. Adding a position vector makes tokens “addressable”, so to speak. So with positional encodings, our simple attention-based model can solve the neighbor task (Figure , right).
I think the most important point here is that the attention mechanism is very, very efficient at capturing sequential information. The attention mechanism with positional encodings is just a few matrix multiplications and additions, and yet can model complex and long-range dependencies between tokens in a sequence.
Causal attention
At this point, we have built up attention from first principles, but we still haven’t talked about a critical step: causality. In words, for many tasks in natural language modeling, a token at position should not be able to “see” the token at position .
Why not? Again, consider the sentence
and imagine we wanted to decode this sequence step-by-step. So “the” predicts “crocodile”, “the crocodile” predicts “swam”, and so on. For every position in the sequence, we ask the model to predict the word that comes next. But if the attention mechanism can see the whole sequence, this task is trivial. The model would learn to copy rather than to predict. We can see this in simple set-based attention experiments above. If you ask the model to find the successor to , it will scan the entire sequence to find it.
The fix is to give the model only the sequence so far and ask it to predict the next token. However, this is forward passes. This is a bit complicated to say in words, but I think it makes sense geometrically (Figure ). At each step, we consider the next query and compare it to all the keys so far. What this should produce is a scores matrix that is lower triangular!
And if we were to implement Figure this naively, we would use a for loop:
def naive_causal_attention(queries, keys, values):
"""
Naive causal attention, processing one token at a time in a for-loop.
"""
n, d = queries.shape
out = np.zeros_like(values)
# Step through n tokens and only attend to the previously processed tokens
for i in range(n):
# Score query i against keys [0, i]
weights = softmax(keys[:i + 1] @ queries[i] / np.sqrt(d))
# Weighted average of values [0, i]
out[i] = weights @ values[:i + 1]
return out
(I ignore the leading dimensions here to simplify the code.) However, this is inefficient. Instead, we could simply compute a matrix-multiplication between and and then mask the upper-triangular bit before normalizing the rows (Figure ).
This is because the attention mechanism at any given step does not depend on the previous step in the for loop. Here is our new attention function, amended to take a mask. As I understand it, this version is pretty close to “production grade” or at least the kind you’ll see in research-level transformer code online. In practice, the mask is not always just a causal mask but can be used to mask padding tokens as well. But conceptually, I think the causal mask is the interesting one.
def attention(queries, keys, values, mask):
"""
Scaled dot-product attention over leading dimensions.
"""
d_k = queries.shape[-1]
# Compute scaled scores, QK^T / sqrt(d_k)
scores = jnp.einsum("...sd,...td->...st", queries, keys) / jnp.sqrt(d_k)
# Apply causal mask: position i only sees j <= i
if mask is not None:
scores = jnp.where(mask, scores, -jnp.inf)
# Compute attention weights, softmax(QK^T / sqrt(d_k)).
weights = nnx.softmax(scores)
# Apply values softmax(QK^T / sqrt(d_k))*V
out = jnp.einsum("...st,...td->...sd", weights, values)
return out, weights
As a small ablation, consider a new toy task where each token must predict the largest digit it has seen so far. Without a causal mask, the attention mechanism sees the entire sequence, including future tokens. With a causal mask, each position only sees itself and previous tokens. So what we would expect is that attention with a causal mask can solve this problem, while attention without a causal mask will not, because it cannot “constrain” its attention (Figure ).
In a transformer, we don’t always use causal masking. It depends on various types of attention. This is why having some intuition for what it does is so important. For example, in the encoder of an encoder–decoder transformer, we don’t need causal masking. The model can see everything. But when in the decoder, we might, if we want to enforce left-to-right causality common in problems like natural language modeling.
Like positional encodings, masking is simple and elegant. If we have a very large sequence, we can still train it on next-token prediction at every subsequence in parallel. And it is remarkably efficient.
Cross-attention
So far, the queries, keys, and values have always come from the same sequence, called self-attention. However, consider the task of translating “the crocodile swam in the ocean” into French. When the model is predicting the French word “nageait”, it needs to look at the relevant parts of the English source sentence, based on the French it has generated so far. In cross-attention, the queries come from one sequence (here, the French translation), while the keys and values come from another sequence being looked up (here, the English sentence) (Figure ).
Coding cross-attention is as easy as passing in different arguments to our attention module. This is not a conceptually challenging extension from self-attention, but I found it confusing initially because I had no purchase on what “query”, “key”, or “value” meant. With these concepts well-grounded, cross-attention is a small leap.
In practice, we can implement all types of attention (self, cross, causal) by simply passing all the variables (queries, keys, values, masks) through:
class Attention(nnx.Module):
def __init__(self, model_dim, rngs):
self.w_q = nnx.Linear(model_dim, model_dim, rngs=rngs)
self.w_k = nnx.Linear(model_dim, model_dim, rngs=rngs)
self.w_v = nnx.Linear(model_dim, model_dim, rngs=rngs)
def __call__(self, query, key, value, mask):
"""
Forward pass of single-headed attention.
"""
# Learn queries, keys, values
query = self.w_q(query)
key = self.w_k(key)
value = self.w_v(value)
# Attend
z, w = attention(query, key, value, mask)
return z, w
And here is an illustrative decoder layer that would use both self- and cross-attention. In self-attention, each French token looks up the French tokens before it. In cross-attention, French queries look up English keys and values. Notice that cross-attention does not need a causal mask, because the whole English sentence is known prior to decoding. (In practice, we might actually supply a mask to remove padding tokens.)
class DecoderLayer(nnx.Module):
def __init__(self, model_dim, rngs):
self.self_attention = Attention(model_dim, rngs)
self.cross_attention = Attention(model_dim, rngs)
def __call__(self, x, enc_out, causal_mask):
"""
Forward pass of decoder layer.
"""
x, _ = self.self_attention(x, x, x, causal_mask)
x, _ = self.cross_attention(x, enc_out, enc_out, mask=None)
return x
The thing to note here is that self- and cross-attention use the same attention module, just with different arguments.
Multi-headed attention
Attention is a powerful mechanism, but hopefully it is clear that we might want to pay attention to the same sequence(s) in different ways. This would give us more flexibility in what we can model, more representational power. Let’s call each sub-module of attention a “head”. The naive way to implement multiple heads of attention would be to simply loop over multiple instantiations of the full attention mechanism:
d_k = model_dim // n_heads
heads = [
(
nnx.Linear(model_dim, d_k, rngs=rngs),
nnx.Linear(model_dim, d_k, rngs=rngs),
nnx.Linear(model_dim, d_k, rngs=rngs)
)
for _ in range(n_heads)
]
...
out = []
for (w_q, w_k, w_v) in heads:
z, _ = attention(w_q(h), w_k(h), w_v(h), mask)
out.append(z)
out = jnp.concatenate(out, axis=-1)
However, once again, as we have seen before, (multi-headed) attention is extremely efficient because we can take this for loop and convert it into matrix multiplications. To see this, consider new multi-headed attention module below.
The key point is that we simply reshape our data, call our attention function, and then reshape our data back. There aren’t “multiple heads” anywhere. It’s just tiling. So if model_dim=64 and n_heads=8, then d_k=8, so the dimension of the queries, keys, and values is . If model_dim=128 for heads, then the dimension of the queries, keys, and values doubles as well. In principle, I don’t know that model_dim has to be a multiple of n_heads, but it makes the implementation cleaner here. But clearly, this implementation is a full generalization of the original Attention module’s, since we can replicate the old behavior with n_heads=1, although in practice, a final linear layer typically mixes the concatenated head outputs.
class MultiheadAttention(nnx.Module):
def __init__(self, model_dim, n_heads, rngs):
self.n_heads = n_heads
self.d_k = model_dim // n_heads
self.w_q = nnx.Linear(model_dim, model_dim, rngs=rngs)
self.w_k = nnx.Linear(model_dim, model_dim, rngs=rngs)
self.w_v = nnx.Linear(model_dim, model_dim, rngs=rngs)
def __call__(self, query, key, value, mask):
"""
Forward pass of multi-headed attention.
"""
batch_size, seq_len, model_dim = query.shape
# Learn queries, keys, values
query = self.w_q(query)
key = self.w_k(key)
value = self.w_v(value)
# Note: d_k * n_heads = model_dim, so:
# Take model_dim-dimensional vector and split it into n_heads chunks.
query = query.reshape(batch_size, -1, self.n_heads, self.d_k)
key = key.reshape(batch_size, -1, self.n_heads, self.d_k)
value = value.reshape(batch_size, -1, self.n_heads, self.d_k)
# Before transpose: query, keys, and values have shape (batch, seq, head, d_k)
# After transpose: they have shape (batch, head, seq, d_k)
query = jnp.transpose(query, (0, 2, 1, 3))
key = jnp.transpose(key, (0, 2, 1, 3))
value = jnp.transpose(value, (0, 2, 1, 3))
# Apply attention across the heads in batch
z, w = attention(query, key, value, mask)
# This effectively concatenates the head outputs. First put back dimensions,
# (batch, head, seq, d_k) -> (batch, seq, head, d_k), then reshape to
# (batch, seq, model_dim)
z = jnp.transpose(z, (0, 2, 1, 3))
z = z.reshape(batch_size, seq_len, model_dim)
return z, w
As a minor point, notice that previously we considered , but this is no longer true.
Embarrassingly parallel
The transformer has eaten the world, and attention is the core mechanism inside the transformer. Of course, the transformer has many other pieces: residual connections, layer normalization, feedforward networks, and so forth. But all-attention was the genuinely novel bit. The goal of this post was to explain attention, but I think the obvious take-away is not so much why it works but why it scales. Every operation can be reduced to a simple matrix operation.
The relevance-based scores? Just compute them via the dot product so that we can parallelize the computation across queries using a matrix multiplication. Positional encoding? Just a matrix addition. Causal masking? Just an element-wise mask. Multi-headed attention? Reshape your data and then another matrix multiplication. In the end, implementing attention is as easy as a handful of matrix operations.
To be clear, attention still has to compute an scores matrix, and so memory and compute scale quadratically with sequence length. However, within a layer, attention has no sequential dependencies across positions. And we can enforce causality as needed using masking, which is an element-wise matrix operation. Thus, we can parallelize across the entire sequence using modern hardware.
- Bahdanau, D., Cho, K., & Bengio, Y. (2014). Neural machine translation by jointly learning to align and translate. ArXiv Preprint ArXiv:1409.0473.
- Cho, K., Van Merriënboer, B., Bahdanau, D., & Bengio, Y. (2014). On the properties of neural machine translation: Encoder-decoder approaches. ArXiv Preprint ArXiv:1409.1259.
- Cho, K., Van Merriënboer, B., Gulcehre, C., Bahdanau, D., Bougares, F., Schwenk, H., & Bengio, Y. (2014). Learning phrase representations using RNN encoder-decoder for statistical machine translation. ArXiv Preprint ArXiv:1406.1078.
- Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention is all you need. Advances in Neural Information Processing Systems, 30.