Transformer Architecture and Attention


Transformer Architecture and Attention

Hope
Welcome back. Today we’re unpacking transformers: what they’re made of, why attention matters, and how the same basic recipe can work with images, language, and other kinds of data. One useful theme to keep in mind is that familiar ideas can take on new meaning when you combine them in a new way.

Maria
And this is a practical look at one particular architecture, not a claim that architectures never change. The big picture is three ideas: represent data as tokens, use attention to decide how information should be combined, and use positional encodings when the order or location of tokens matters.

Hope
Let’s begin with the problem that motivates attention. A convolutional neural network is built around local filters. That’s often a good bias: if we’re understanding what’s happening in a room, we usually don’t need to inspect Mars. But some questions depend on relationships between distant parts of an input.

Maria
For example, a CNN might count birds in an image by detecting local features and aggregating them. But suppose we want to know whether the bird at the top right is the same species as the one at the bottom left. A sufficiently deep CNN could connect those regions, but local information has to spread layer by layer, so it may not be the most direct way to reason about that relationship.

Hope
A small receptive field makes the issue concrete. In a convolutional layer with a filter of length three, each output depends on only a local group of inputs. After another layer, the receptive field expands, but only gradually. In a shallow network, there may be no output that has received information from both of two distant inputs, so the network can’t yet make a decision based on their joint configuration.

Maria
A fully connected network avoids that particular limitation: every output can immediately use every input. But it can require a huge number of connections and parameters. Attention aims for a middle ground: make global information available, while allowing the model to give more weight to the parts that matter for the current computation.

Hope
That’s the intuition behind the word ‘attention.’ If the question is how many birds there are, the model should emphasize bird regions. If the question is about the sky’s color, it should emphasize the sky. The important idea is that the relevant information can change with the task or with the token doing the processing.

Maria
Before attention, though, we need to say what the model operates on. In this lecture, a token is a vector of numbers—a bundle of information treated as one unit. That’s a broader use of the word than in much natural-language processing, where ‘token’ often means a discrete vocabulary item, such as a word or a word fragment.

Hope
Here, think of tokens as the chunks into which we factorize a problem. In a graph neural network, a node’s feature vector could be treated as a token. In an image transformer, a token might represent an image patch. The key shift is from processing an array of scalar-valued neurons to processing an array of vector-valued units.

Maria
To make image tokens, a standard approach is to divide the image into patches, flatten each patch’s pixel values into a vector, and project that vector into a chosen dimension. The projection can be learned. In common designs, the patches don’t overlap, though overlap is a possible design choice.

Hope
The same principle works across domains, but the way you make tokens is domain-specific. Language models might split text into subword pieces; audio can be divided into chunks. Once the data has been turned into tokens, the transformer’s processing machinery can be much more general-purpose.

Maria
Usually all tokens have the same vector dimension, which makes the representation and computation straightforward. We can stack them as rows of a matrix: with n tokens and d features per token, the token matrix has n rows and d columns. Treating the tokens as an unordered set will be important later.

Hope
A token network still uses familiar neural-network building blocks. One is a linear combination. Instead of taking a weighted sum of individual scalar neurons, we can take a weighted sum of whole token vectors. If there are three tokens, for instance, we can combine them using three weights, applying each weight to the entire vector.

Maria
That’s a more restricted operation than assigning a separate weight to every scalar in every token. It behaves like a lower-rank transformation over all the underlying neurons. But it fits the idea that each token is an encapsulated unit, and it can be an efficient way to mix information between those units.

Hope
The other familiar building block is a nonlinearity. A standard neural network applies a pointwise function, such as ReLU, to scalar activations. A token network applies the same token-wise function to each token independently. In transformers, that function is typically an MLP, so each token gets processed by a small neural network.

Maria
Put those pieces together and you have a repeated pattern: combine tokens, apply a learned nonlinear transformation to each token, and repeat. This resembles an unrolled graph neural network. A graph network aggregates according to the graph’s connections; a transformer can be viewed as a graph network on a fully connected graph, with attention determining the strengths of the connections.

Hope
That brings us to the genuinely distinctive idea: how do we set those strengths? One option would be to make every combination weight a free parameter. Attention instead makes the weights depend on the data being processed. The same model can therefore combine tokens differently in different situations.

Maria
Imagine asking how many animals appear in a photo. A token might represent a patch containing an animal’s head, and its features might indicate whether an animal head is present. The model could give those tokens high attention, give other patches low attention, and combine the selected information to produce a count.

Hope
Or ask for the impala’s color. Now the model should focus on patches associated with the impala and combine information about their colors. These examples are a way to build intuition: attention chooses which information to gather, while the token features carry the information that gets gathered.

Maria
The standard mechanism is called query-key-value attention. A query expresses what a token is looking for. A key describes what another token has to offer for matching. A value is the information that token contributes if it receives attention.

Hope
The query, key, and value are learned linear projections of token vectors. To compare a query with a key, the model takes their dot product. A larger similarity score means that token is a better match for the query, and the scores are turned into attention weights with a softmax.

Maria
Then the output is a weighted sum of the value vectors. So the query and key determine how much attention each token gets, while the values determine what information is passed along. Those three projection matrices—one each for queries, keys, and values—are learned by the model.

Hope
In the basic query-key-value setup, a query could come from a separate question, such as text asking about an image. In self-attention, the queries come from the tokens in the input itself. Each token can then ask what it should take from the other tokens in that same set.

Maria
For instance, a patch that is uncertain about what it depicts could attend to other patches that look related and use their information to update its representation. In visual recognition, attention sometimes appears to group parts of the same object—for example, horse patches attending to other horse patches. That’s an empirical behavior the model can learn, not a rule that the architecture guarantees.

Hope
It’s useful to keep that distinction clear. The attention mechanism and its parameters are learned through training to meet an objective. We can inspect the patterns it learns and try to interpret them, but a plausible interpretation isn’t automatically a proof of why the model works.

Maria
For self-attention, stack every token’s query into a query matrix, and do the same for keys and values. The attention scores come from multiplying the query matrix by the transpose of the key matrix. That gives a score for every query-token and key-token pair.

Hope
In the usual scaled dot-product form, divide those scores by the square root of the query and key dimension, apply softmax, and multiply the resulting attention matrix by the value matrix. The scaling and normalization are part of the standard recipe. In compact form, it’s queries times keys-transposed, scaled and softmaxed, then multiplied by values.

Maria
There’s a practical reason for using learned query and key projections rather than simply learning an arbitrary attention matrix for every input length. A directly learned matrix would have a number of parameters tied to the square of the sequence length. The projection matrices instead depend on feature dimensions, which can be more practical when sequences are very long.

Hope
Attention is one kind of token-mixing layer, but it’s helpful to compare it with others. A fully connected layer learns a general matrix of connections. A convolution uses shared weights and a structured pattern of connections, which gives it properties such as translation equivariance. Attention also mixes tokens, but its weights are computed from the input.

Maria
Transformers often use multiple attention heads in parallel. Each head can learn a different way to relate tokens—for example, one might emphasize one kind of feature and another a different kind—and their results are then combined. The transformer also typically includes token-wise MLPs, residual connections, and LayerNorm.

Hope
A residual connection gives information a path around a processing block. LayerNorm normalizes the components of a token’s vector, commonly by subtracting its mean and scaling by its variance. These are part of the standard transformer design, and they have useful optimization properties, even though the precise reasons this recipe works so well remain an active area of investigation.

Maria
So the overall vision-transformer pattern is: tokenize the input, then repeatedly apply attention and token-wise processing, with residual connections and normalization. Much of the computation can be expressed as matrix multiplications, which suits modern hardware. The main domain-specific work happens in how the input is tokenized and how location is represented.

Hope
That location issue matters because, without extra information, a transformer is permutation equivariant. If you reorder the input tokens, the outputs reorder in the same way. Token-wise MLPs treat tokens identically, and attention compares their contents rather than relying on their row positions.

Maria
That’s useful when the input really is an unordered set, but often order matters. In a sentence, the word positions affect meaning and prediction. In an image, a patch’s location is important. Positional encodings give each token information about where it came from, so the model can distinguish tokens that otherwise have the same content but occupy different positions.

Hope
One common approach is to encode position with sinusoidal or Fourier-style features, such as sine and cosine values at different frequencies. For an image, those features can represent horizontal and vertical position. This is an example of supplying an inductive bias about locality and structure, rather than expecting the model to infer position from an unordered collection alone.

Maria
The representation can be adapted to the domain. On a globe, positional features might reflect latitude and longitude or spherical harmonics. For a graph, a positional encoding can use eigenvectors of the graph Laplacian. The general lesson is that positional encoding is a place to incorporate knowledge about what location means for the data.

Hope
Now let’s connect transformers to language models. An autoregressive language model predicts the next token from the tokens that came before it. It is trained on sequences of text, and at generation time it predicts a next token, appends that prediction, and repeats.

Maria
That’s the basic idea behind GPT: a Generative Pre-trained Transformer used autoregressively. But training introduces a potential shortcut. If the model can see the answer token it is supposed to predict, it might simply copy it rather than learn to predict it from earlier context.

Hope
Causal attention prevents that shortcut. A causal mask blocks a token from attending to later tokens in the sequence. Each position can use earlier positions, and typically itself where appropriate, but it cannot use future information to make its prediction.

Maria
With the mask in place, the model can produce predictions for many positions in parallel during training, while each prediction still depends only on the allowed preceding context. At generation time, the model uses the available sequence to predict one more token, appends it, and runs the process again.

Hope
The original transformer recipe brings together these components: attention, token-wise feedforward processing, residual connections, normalization, and positional information. For language generation, causal masking supplies the restriction that makes predictions depend on previous tokens rather than future ones.

Maria
And transformers can also connect different kinds of tokens. For image captioning, one part of the model processes image patches into image tokens, while another generates words one at a time. Cross-attention lets the text-generation tokens attend to the image tokens, as well as to the earlier words in the caption.

Hope
That’s the broader pattern: turn each kind of input into useful tokens, use attention to move information between relevant tokens, and add structure such as positional encodings or causal masks when the task requires it. The details vary, but those three ideas—tokens, attention, and position—explain much of the transformer architecture.

Ask anything
We've read this whole study set, so questions about it get the best answers.