Transformer Architecture and Attention
Transformers: Core Ideas and Architecture
Why Transformers Were Developed
A convolutional neural network (CNN) processes information through local operations. Each convolutional filter sees only a small region, and deeper layers gradually combine information from wider regions. This local structure is useful when nearby parts of a signal are most relevant, as they often are in images.
However, some tasks depend on relationships between distant parts of an input. For example, identifying whether two birds in opposite corners of an image are the same species requires comparing distant regions. A CNN can eventually make this comparison if it is deep enough, but local information must pass through multiple layers before the regions can interact.
A fully connected network gives every output access to every input immediately, but this can require a very large number of parameters and computations. For a mapping from Rn to Rn, a general fully connected layer has n2 weights.
Attention offers another approach: it allows information to be combined globally, while making the combination depend on which parts of the input are relevant. For a question about the birds, the system can assign greater weight to the bird regions; for a question about the sky, it can assign greater weight to the sky. Thus, attention provides a way to select relevant information dynamically rather than always combining inputs in the same fixed way.
Transformers combine vector-valued units called tokens, attention-based information exchange, and positional information when the order or location of tokens matters.
Tokens: The Units a Transformer Processes
What a token represents
In this framework, a token is a vector representing a unit of information. A token can be thought of as a compact, encapsulated bundle of features that is processed as a unit.
In a graph, a token may correspond to a node’s feature vector.
In an image, a token may represent a patch.
In language, a token may represent a word or a subword unit.
In audio, a token may represent a segment of the signal.
Transformers are built to operate over sets or sequences of these vector-valued units, rather than directly over individual scalar-valued neurons.
The term token is used somewhat differently across fields. In natural-language processing, it often means a discrete vocabulary item, such as a word or subword. In the broader architectural sense used here, it means the vector representation of a chunk of information.
Converting data into tokens
A transformer needs a way to convert its input domain into tokens. This conversion is often domain-specific; much of the processing that follows can then use a general transformer architecture.
For an image, a common process is:
Divide the image into patches, usually non-overlapping patches in standard vision-transformer designs.
Flatten the pixel values in each patch into a vector.
Project that vector into a chosen token dimension.
If a patch is represented by a vector x, a simple projection is
where Wtokenize maps the patch representation into the token space. This projection can be learned or specified in advance. Once projected, each patch is represented by a vector of the same dimension as the other tokens.
For language, the input is divided into discrete units such as words or subwords. A common approach uses byte-pair encoding, which builds subword units from recurring character sequences. The resulting units are then represented by vectors for transformer processing.
Token design is a source of domain knowledge. Local patches are a natural choice for images, while linguistic subunits are natural for text. Different tokenization choices can change how effectively the model represents its input.
Representing a collection of tokens
Suppose there are n tokens, each with dimension d. They can be stacked as the rows of a matrix:
Here:
n is the number of tokens.
d is the number of features, or channels, in each token.
Each row of T is one token vector.
Standard transformer designs generally use the same dimension for every token. Variable-sized tokens are possible in principle, but require additional handling and can be less convenient for efficient hardware operations.
Operations Over Tokens
Transformer computations reuse familiar neural-network ideas, but apply them to vector-valued tokens rather than scalar-valued neurons.
Linear combinations of tokens
A linear combination over tokens combines whole token vectors. If T contains n tokens and w∈Rn contains one weight per token, then
is a weighted combination of the rows of T.
This is more constrained than assigning an independent weight to every scalar feature in every token. The same token-level weight is applied across the dimensions of that token. In that sense, this operation imposes structure on the transformation and can be viewed as a lower-dimensional alternative to an unrestricted linear operation over all the individual scalar features.
Token-wise nonlinearities
A token-wise nonlinearity applies the same function independently to every token. If F is the function applied to each token, then
for token index i.
In transformers, F is commonly a multilayer perceptron (MLP). The same MLP is applied separately to every token, allowing the representation of each token to be transformed nonlinearly without mixing it with other tokens in that operation. This resembles a 1×1 convolution applied across a sequence: each location is transformed using the same function.
Relation to MLPs, CNNs, and graph neural networks
A transformer block combines two broad kinds of operations:
Mixing information across tokens, using attention.
Transforming each token independently, using a token-wise MLP.
This resembles familiar neural-network patterns:
An MLP combines scalar-valued units and then applies nonlinearities.
A token network combines vector-valued units and then applies token-wise nonlinearities.
A graph neural network (GNN) aggregates information from neighboring nodes and updates node representations.
A GNN’s aggregation pattern is determined by the graph’s connectivity. A transformer’s attention can be understood as information exchange on a fully connected token graph: every token can potentially interact with every other token. The strength of each interaction is determined by attention.
Transformers and GNNs can both use separate parameters at different depths, or share parameters across layers. Standard transformers usually use different learned parameters at different layers; weight sharing is possible but is not required.
Attention: Data-Dependent Information Mixing
Fixed weights versus attention weights
A basic token-mixing layer could use fixed learned weights, just as an ordinary linear layer does. Attention instead makes the mixing weights depend on the input data.
This matters because the relevant tokens can change with the task or the contents of the input. The attention mechanism calculates which tokens should contribute more strongly, then uses those calculated weights to combine token information.
An intuitive example is counting animals in an image. If each image patch has a representation that indicates whether it contains an animal, attention can assign high weights to the animal patches and low weights elsewhere. A weighted sum of those representations can then support a count. For a question about the color of a particular animal, attention can instead emphasize patches belonging to that animal and combine their color information.
Query, key, and value
The most common formulation is query-key-value attention. Each token is projected into three vectors:
A query represents what the token is looking for.
A key represents what information the token offers for matching.
A value represents the information that will be passed along if the token is attended to.
For an input token matrix T, the projections are commonly written as
where WQ, WK, and WV are learned projection matrices.
A query is compared with keys using dot products. A larger query-key dot product indicates a stronger match in the learned representation space. For example, a query asking about an impala’s head should receive a high score for keys associated with impala-head patches.
The value is distinct from the key: the key helps determine where to look, while the value carries what is retrieved from the selected token.
The attention calculation
For a collection of queries, keys, and values, the standard scaled dot-product attention operation is
where dk is the dimension of the key and query vectors.
The calculation proceeds as follows:
Calculate similarities: QK⊤ gives a score for each query-key pair.
Scale the scores: divide by dk to keep score magnitudes from growing excessively as the vector dimension increases.
Normalize the scores: apply softmax across the keys for each query. This produces weights that sum to 1.
Combine values: use the normalized weights to form a weighted sum of the value vectors.
The resulting attention-weight matrix has one row per query and one column per key. Its entries specify how strongly each query attends to each token’s value.
The query, key, and value projections are learned during training. The attention weights themselves are calculated from the current inputs, rather than being independent, fixed parameters for every possible token pair.
Why use query-key projections?
An alternative would be to learn an unrestricted attention matrix directly, but that would require a separate parameter for every token pair and would depend on the sequence length. Query-key attention instead computes pairwise scores from learned token projections. The learned projection dimensions need not grow with the number of tokens, which makes the parameterization more practical for long sequences.
The attention calculation still compares tokens with one another, so standard attention can require substantial computation for very long sequences. Its advantage is that the pairwise weights are generated from shared projections, rather than stored as an independent parameter for each possible pair.
Self-Attention
In self-attention, queries, keys, and values all come from the same input set of tokens. Each token can use its query to decide which other tokens’ values are relevant to its representation.
For example, a patch that is uncertain about whether it belongs to a particular animal could attend to other patches that appear related. Combining their information can help refine its representation. In a visual recognition system, attention may learn patterns in which patches belonging to the same object attend strongly to one another.
Self-attention does not guarantee that an intuitive pattern will emerge. The model learns its projections and attention behavior through optimization for the training objective. The learned attention may be interpretable, but it can also use strategies that are less obvious to a human observer.
With n input tokens, self-attention computes pairwise interactions between tokens, producing an n×n score or attention matrix before the values are combined.
Multi-head self-attention
A transformer often uses multi-head self-attention rather than a single attention operation. Multiple attention heads operate in parallel, each with its own projections. The heads’ outputs are then combined.
Different heads can learn to capture different kinds of relationships—for example, one head may emphasize shape-related information while another emphasizes texture or other contextual relationships. The roles of individual heads are learned rather than assigned in advance.
How Transformers Differ from CNNs
A CNN uses local filters and shared weights. Its structure gives it a strong locality bias: nearby regions interact directly, while distant regions generally require information to pass through multiple layers.
A transformer instead uses attention to create input-dependent interactions between tokens. This allows distant tokens to exchange information within an attention layer, without requiring the same gradual expansion of receptive fields as in a CNN.
The two approaches encode different assumptions:
CNNs: local relationships are fundamental, and the same filters are reused across locations.
Transformers: tokens can interact according to content-dependent relationships, and those interactions can be global.
Tokenization and positional encoding: provide ways to retain useful structure and domain knowledge rather than treating the input as completely unstructured.
Attention can focus strongly on a small subset of tokens, but standard self-attention usually calculates scores for all token pairs. Its weights are therefore not inherently sparse, even when their learned values become concentrated on only a few tokens.
Common Vision-Transformer Structure
A vision transformer first turns an image into a sequence or set of patch tokens. It then applies repeated transformer blocks to those tokens. A typical block contains:
Multi-head self-attention, which mixes information between tokens.
A token-wise MLP, which transforms each token independently.
Residual connections, which add the input of a sublayer to its output.
Normalization, commonly LayerNorm, which normalizes each token’s activations.
A residual connection preserves a direct path for the original representation. A sublayer can therefore add a learned update to the existing token representation rather than needing to reconstruct the entire representation from scratch.
LayerNorm typically normalizes the features within a token by centering them and scaling them according to their variance. It acts on activations, not directly on the weight updates. Normalization is used in transformer architectures because it supports effective optimization, although the precise reasons it helps are an active subject of investigation.
At a high level, a transformer layer repeatedly performs matrix operations on the token representations, together with nonlinearities, normalization, and residual additions. This structure maps well to hardware optimized for matrix multiplication.
Permutation Equivariance and Positional Information
Why ordinary attention does not encode order
Without positional information, a transformer treats tokens according to their content, not according to the order in which they appear. Its token-wise MLP applies the same function to every token, and self-attention compares token representations without inherently knowing which token came first.
As a result, if the input tokens are permuted, the output tokens are permuted in the corresponding way. This property is called permutation equivariance. The model’s outputs follow the rearrangement of the inputs, but the model does not independently know that one token occupied an earlier position or a particular location.
This is useful when the input is genuinely an unordered set. It is insufficient when order or location carries meaning, as it does in sentences, time series, and images.
Positional encodings
A positional encoding supplies information about where each token came from. It can represent, for example:
A word’s position in a sentence.
A patch’s location in an image.
A node’s position or structural role in a graph.
A point’s location on a globe.
The positional information can be combined with token information in different ways, such as by adding it to the token representation or appending it as additional features. A common approach uses sinusoidal or Fourier-style functions of position rather than only raw Cartesian coordinates. For an image, the encoding can represent both horizontal and vertical location through multiple sine and cosine functions.
The choice of positional encoding is another place to incorporate domain structure:
Images: horizontal and vertical coordinates can describe patch locations.
Spherical data: latitude and longitude, or spherical harmonics, can describe positions on a globe.
Graphs: eigenvectors of the graph Laplacian can provide structural coordinates for nodes. These eigenvectors can function somewhat like a graph-specific frequency basis, ranging from broad, smooth patterns to more rapidly changing ones.
Positional encodings give a transformer information about locality and arrangement that would otherwise be absent from content-only attention.
Autoregressive Language Modeling and Causal Attention
Predicting the next token
An autoregressive model predicts the next item in a sequence from the items that came before it. For language, it learns to predict the next word or subword from the preceding text. Generation then proceeds step by step:
Provide an initial context.
Predict the next token.
Append the prediction to the context.
Predict another token from the expanded context.
Repeat.
The model is trained using examples from text sequences, with the next observed token serving as the target. During generation, it produces new tokens based on its learned predictions.
GPT—Generative Pre-trained Transformer—uses a transformer in this autoregressive way.
Why causal masking is required
If a model is trained to predict a token while also seeing that token as input, it could simply copy the answer. To prevent this, autoregressive transformers use causal attention: each token may attend only to itself and earlier tokens, not to later tokens.
A causal mask sets attention scores for forbidden future positions so they cannot contribute. This changes the attention pattern from unrestricted self-attention to an ordered pattern in which information flows only from earlier positions to later ones.
During training, the input sequence is shifted relative to the target sequence so that each position predicts the next token. Causal masking ensures that the prediction at a given position uses only the available past, allowing the model to learn to generate a sequence one step at a time.
Causal masking also means that the model is no longer permutation equivariant: the sequence order matters because the mask explicitly distinguishes earlier positions from later ones.
Cross-Attention and Image-to-Text Tasks
Cross-attention allows one set of tokens to attend to a different set of tokens. Unlike self-attention, the queries and the keys and values come from separate token collections.
For image captioning:
The image is converted into patch tokens.
The image tokens are processed to build visual representations.
A language-generation process produces caption tokens autoregressively.
Each text-generation step can attend to the image tokens as well as to the earlier words in the caption.
This combines two information sources: the words already generated and the visual content of the image. More generally, cross-attention provides a way to connect different modalities or separate components of a model, while self-attention handles interactions within a single set of tokens.

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